c++動態載入dll中的類(用於實現依據字串類名建立對象)

來源:互聯網
上載者:User

參考資料:

http://blog.csdn.net/yysdsyl/archive/2008/07/08/2626033.aspx

用來產生dll的檔案:

////////////////////////////Test.hclass Test{public:    Test(void);public:    virtual ~Test(void);public:    virtual void DoSth()=0;};

--------------------------------------------

 

///////////////////TTest.h/////////////TTest繼承自Testclass TTest :    public Test{public:    TTest(void);public:    ~TTest(void);public:    virtual void DoSth(){std::cout<<"TTest:do sth/n";};};
///////////關鍵extern "C" __declspec(dllexport) Test* CreateTTestPtr();extern "C" __declspec(dllexport) void DeleteTTestPtr(Test* t);

 

--------------------------------------------------

////////////////TTest.cpp#include "TTest.h"TTest::TTest(void){}TTest::~TTest(void){    std::cout<<"destruct TTest/n";}Test* CreateTTestPtr(){    return new TTest();}void DeleteTTestPtr(Test* t){    if(t!=NULL)        delete t;}
測試程式:
#include "Test.h"#include <Windows.h>typedef Test* (CREATEFN)();typedef void (DELETEFN)(Test* );int _tmain(int argc, _TCHAR* argv[]){    HINSTANCE hd=::LoadLibrary("AnotherDll.dll");    CREATEFN* pfn;    DELETEFN* xfn;    pfn=(CREATEFN *)::GetProcAddress(hd,"CreateTTestPtr");    xfn=(DELETEFN *)::GetProcAddress(hd,"DeleteTTestPtr");        Test* t=(*pfn)();    t->DoSth();    (*xfn)(t);    getchar();    return 0;}
 
 
 
-------------------------------------------------------------------
 
向dll中添加新的繼承於Test基類時,實現自身的同時實現下面的兩函數
extern "C" __declspec(dllexport) Test* CreateXXXPtr();extern "C" __declspec(dllexport) void DeleteXXXPtr(Test* t);
 
(其中XXX表示新添加的類的類名,當然命名可以隨意,只要你能在應用程式中找到這兩匯出函數,不過統一的命名規則
對根據類名建立對象是有好處的)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.