C++動態加載(顯式鏈接)使用類接口

C++動態加載(顯式鏈接)使用類接口

使用windows下的工程 ,動態加載DLL(顯示鏈接),靈活性更好,相比隱式鏈接,無需在工程設置.lib

示例:

代碼片 dll 中的 getestui.h. 自己在VS中設置會生成的dll叫 getest.dll

// 需要使用虛基表的方法,才能動態加載時,使用類的接口

# ifdef BUILD_GAMEECOLOGY_DLL
#   define GAMEECOLOGY_EXPORT __declspec(dllexport)
# else
#  define GAMEECOLOGY_EXPORT __declspec(dllimport)
# endif // BUILD_GAMEECOLOGY_DLL

class GeTestUI 
{
public:
	GeTestUI();

	virtual void creatMessage();//注意要用虛函數

	virtual void deleteSelf();//注意要用虛函數
};

extern "C" GAMEECOLOGY_EXPORT GeTestUI *createGeTestUiObject();//對外提供構造函數

代碼片 dll 中的 getestui.cpp

#include "getestui.h"

GeTestUI::GeTestUI()
{

}

void GeTestUI::creatMessage()
{
	//QMessageBox::warning(0, "hello", "Test Now!!"); 寫一些代碼
}

void GeTestUI::deleteSelf(void)
{
	delete this;
}

GeTestUI *createGeTestUiObject()
{
	return new GeTestUI();
}

外部工程的main.cpp使用動態加載.

// 
	typedef GeTestUI* (CREATEFN)(void);
	HMODULE  hModule = LoadLibraryEx(L"getest.dll", NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
	CREATEFN* pfn;
	pfn=(CREATEFN *)::GetProcAddress(hModule,"createGeTestUiObject");
	GeTestUI *testUi = pfn();
	testUi->creatMessage();//這裏就是要使用 virtual ,虛基表的機制,不然會編譯出錯
	testUi->deleteSelf();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章