1.環境
Ubuntu 14.04
g++ 4.8.4
2.有類的情況
1)庫文件
a)源碼
//cppl2.hclass cal {public:	cal();	virtual ~cal();	virtual int add(int a, int b);};typedef cal* (*creat_t)();typedef void (*destroy_t)(cal*);//cppl2.cpp#include "cppl2.h"cal::cal(){};cal::~cal(){}int cal::add(int a, int b) {	return a + b;}//typedef cal* create_c();//typedef void destroy_c(cal*);extern "C" cal* create(){	return new cal;}extern "C" void destroy(cal* c) {	delete c;}b)編譯成可執行文件cd到cppcppl2.cpp所在目錄,輸入命令
g++ -fPIC -shared -o libcppl2.so cppl2.cpp會在當前目錄生成文件libcppl2.so2)主程序a)源碼
//cppcppl2.cpp#include <stdio.h>#include <dlfcn.h>#include "cppl2.h"using namespace std;int main() {	void* handle;	handle = dlopen("./libcppl2.so", RTLD_LAZY);	creat_t createcal = (creat_t)dlsym(handle, "create");	destroy_t destroycal = (destroy_t)dlsym(handle, "destroy");	cal* _cal = createcal();	int result = _cal->add(3, 4);	PRintf("%d/n", result);	destroycal(_cal);	dlclose(handle);	return 0;}b)編譯成可執行文件cd到cppcppl2.cpp所在目錄,輸入命令
g++ cppcppl2.cpp -o cppcppl2 -ldl3)執行
cd到可執行文件cppcppl1所在目錄
輸入命令
./cppcppl2
新聞熱點
疑難解答
圖片精選