如何在命名空间内导入C++类的dll

acc*_*ews 5 c++ dll explicit dllimport linkage

我读了一些文档,给出了与C兼容的功能的简单示例.

__declspec(dllexport) MyFunction();
Run Code Online (Sandbox Code Playgroud)

我很开心.我写了一个小应用程序使用这个dll的功能.我使用显式链接

LoadLibrary() 
Run Code Online (Sandbox Code Playgroud)

功能.C风格的功能没有问题.但是当我把我的班级写成

namespace DllTest
{
class Test
{
public:
    __declspec(dllexport) Test();
    __declspec(dllexport) void Function( int );
    __declspec(dllexport) int getBar(void);
private:
    int bar;
};

}
#endif
Run Code Online (Sandbox Code Playgroud)

它编译得很好,并且创建了Dll.使用C风格函数时,我只是从LoadLibrary()和GetProcAddress(...)函数中获取函数指针.

我之前的用法是

typedef void (*Function)(int);

int main()
{
   Function _Function;
   HINSTANCE hInstLibrary = LoadLibrary(TEXT("test.dll"));

   if (hInstLibrary)
   {
      _Function = (Function)GetProcAddress(hInstLibrary,"Function");
     if (_Function)
     {
        // use the function
Run Code Online (Sandbox Code Playgroud)

但现在我不知道如何实例化我的课程?我如何使用显式链接或隐式链接?

任何有关代码示例的帮助将不胜感激.

mfo*_*ini 6

如果您正在尝试实例化一个类,那么您需要在编译时知道它的结构.您可以通过创建一个抽象类来实现此目的,该类定义导入的类必须重新定义的实例方法.例如:

//interface.h

class TestInterface
{
public:
     virtual void Function( int ) = 0;
     virtual int getBar(void) = 0;
};
Run Code Online (Sandbox Code Playgroud)

然后,在您的DLL中,您可以包含interface.h,继承TestInterface并重新定义纯虚方法:

//test.h
namespace DllTest {
    class Test : public TestInterface
    {
    public:
         Test();
         void Function( int );
         int getBar(void);
    private:
        int bar;
    };
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以在DLL中定义一个分配Test对象的函数:

extern "C" __declspec(dllexport) TestInterface *allocate_test() {
    return new DllTest::Test();
}
Run Code Online (Sandbox Code Playgroud)

最后,当您导入DLL时,查找符号"allocate_test"并使用它:

TestInterface *(*test_fun)() = (TestInterface *(*test_fun)())GetProcAddress(hInstLibrary,"allocate_test");
TestInterface *test_ptr = test_fun();
test_ptr->Function(12); //use you object
Run Code Online (Sandbox Code Playgroud)

  • 两点:首先,`TestInterface`不需要(也不应该)私有数据成员,其次,如果他要将函数的名称传递给`GetProcAddress`,函数最好是'extern' C"`(否则,他必须传递受损的名字).当然,在`allocate_test`中,你的意思是`返回新的Test;`,而不是`返回新的TestInterface();`(它不会编译). (2认同)