C ++ dynamically loads classes in DLL (used to create Objects Based on the string class name)

Source: Internet
Author: User

References:

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

Used to generate DLL files:

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

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

 

/// // Ttest. h /////////// ttest inherited from testclass ttest: public test {public: ttest (void); Public :~ Ttest (void); Public: Virtual void dosomething () {STD: cout <"ttest: Do something/N ";};};
//// // Key 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;}
Test procedure:
#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;}
 
 
 
-------------------------------------------------------------------
 
When adding a new class to the DLL that inherits from the test base class, you can implement the following two functions at the same time.
extern "C" __declspec(dllexport) Test* CreateXXXPtr();extern "C" __declspec(dllexport) void DeleteXXXPtr(Test* t);
 
(Xxx indicates the name of the newly added class. Of course, the name can be customized. As long as you can find the two export functions in the application, the naming rules are uniform.
It is good to create an object based on the class name)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.