Linux C++動態庫


C++類頭文件[tdl.h]

#ifndef __TEST_DL_H__
#define __TEST_DL_H__

#include "ctdl.h"

class TestDL:public CTestDL
{
public:
	TestDL(){};
	virtual ~TestDL(){};
	virtual void test(const char *pstr);
	virtual void hello();
};

#endif

 C++類源文件[tdl.cpp]

#include <stdio.h>
#include <unistd.h>

#include "tdl.h"

CTestDL *GetClass_DL(void)
{
	return (new TestDL());
}

void TestDL::hello()
{
	printf("hello,this is library message\n");
}

void TestDL::test(const char *pstr)
{
	printf("USE library say:%s\n",pstr);
}

 C++類庫外部引用文件[ctdl.h]

#ifndef __CTEST_DL_H__
#define __CTEST_DL_H__


class CTestDL
{
public:
  virtual void test(const char *pstr) = 0;
  virtual void hello() = 0;
};

extern "C" CTestDL *GetClass_DL(void);


#endif

 編譯生成.so動態庫:

  g++ -shared -lc -s -o libtdlc.so tdl.cpp

   使用的時候,只需要libtdlc.so庫文件和ctdl.h頭文件

C++調用庫源文件[test.cpp]

#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>

#include "ctdl.h"

int main(int argc,char **argv)
{
	CTestDL *(*pTestDLObj)(void);
	dlerror();

	void *lib_dl = dlopen("./libtdlc.so",RTLD_LAZY);
	if(NULL == lib_dl)
	{
		printf("load library libtdlc.so error.\nErrmsg:%s\n",dlerror());
		return -1;
	}
	pTestDLObj = (CTestDL *(*)(void))dlsym(lib_dl,"GetClass_DL");
	const char *dlmsg = dlerror();
	if(NULL != dlmsg)
	{
		printf("get class testdl error\nErrmsg:%s\n",dlmsg);
		dlclose(lib_dl);
		return -1;
	}

	CTestDL *pTestdl = (*pTestDLObj)();
	pTestdl->hello();
	pTestdl->test("success");

	delete pTestdl;
	dlclose(lib_dl);
	return 0;
}

 編譯生成應用程序:

  g++ -rdynamic -ldl -s -o test test.cpp

 

剛開始寫動態庫的時候,TestDL類聲明里面沒寫構造和析構函數,在運行test后提示:__ZIXGnCTestDL undefine,加上之后就正常了。這個不知道是什么原因。在TestDL和CTestDL兩個類中都添加構造和析構函數,也會有這個提示。

 

備注:出現__XXXXClass undefine和typeinfo xxxclass / vtable xxxxclass undefine解決方法:

  在定義虛函數時,virtual int test()=0;即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM