现在的位置: 首页 > 综合 > 正文

c++动态加载dll中的类(用于实现依据字符串类名创建对象)

2013年09月08日 ⁄ 综合 ⁄ 共 1420字 ⁄ 字号 评论关闭

参考资料:

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

用来生成dll的文件:

////////////////////////////Test.h

class Test

{

public:

    Test(void);

public:

    virtual ~Test(void);

public:

    virtual void DoSth()=0;

};

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

 

///////////////////TTest.h

/////////////TTest继承自Test

class 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表示新添加的类的类名,当然命名可以随意,只要你能在应用程序中找到这两导出函数,不过统一的命名规则
对根据类名创建对象是有好处的)

抱歉!评论已关闭.