DLL如何导出类?

xiaoxiao2021-02-28  58

其实最好是写一个父类,把要实现的函数全部以虚函数的形式写在父类中,然后写一个子类,继承父类,重写父类的虚函数。这样的话就安全得多了。其次就在DLL中导出一个函数,返回父类的一个对象指针,再在EXE中动态链接DLL,调用导出函数。例子如下: //以下是DLL的代码 //class_a.h class A {   public:     virtual void fun()     {         //...     } } //class_b.h class B : public A {     public:         void fun()         {            //...         } } //dllMain.cpp extern "C" __declspec(dllexport) A* GetObj();  //导出函数,返回一个A类的指针 int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*) {     //....     return 1; } A* GetObj() {     return new B(); } //以下是EXE的代码 #include "class_a.h" typedef A* (*pObj)();  //定义一个函数指针 pObj fun; int WINAPI WinMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in LPSTR lpCmdLine, __in int nShowCmd ) {     HINSTANCE hDll = LoadLibrary(_T("sample.dll"));     if (hDll == NULL)     {         MessageBox(0, _T("加载DLL失败"), _T("Error"), 0);         return -1;     }     //取函数指针     fun = (pObj)GetProcAddress(hDll, "GetObj");     if (fun == NULL)     {         MessageBox(0, _T("加载失败。"), _T("错误"), MB_ICONSTOP);         return -1;     }     A* p = fun();   //调用fun,返回一个A类指针p     //之后就可以通过p来访问DLL中的类了...     return 0; } 在EXE调用的时候,记得要把A类的头文件包含,这样一来就只是访问了A类,而B类通过继承A类并重写A类的虚函数,来实现了功能,因此只有A类(相当于只是虚函数列表)暴露在外面,而B类则完全是在DLL内部实现的。
转载请注明原文地址: https://www.6miu.com/read-74354.html

最新回复(0)