gpt4 book ai didi

c++ - 如何在命名空间中导入 C++ 类的 dll

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:42 26 4
gpt4 key购买 nike

我阅读了一些文档,其中提供了与 C 兼容的函数的简单示例。

__declspec(dllexport) MyFunction();

我对此很满意。我写了一个小应用程序使用这个dll的功能。我使用了显式链接

LoadLibrary() 

函数。 C 风格的函数可以毫无问题地工作。但是当我把我的课写成

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

}
#endif

它编译良好并创建了 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

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

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

最佳答案

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

//interface.h

class TestInterface
{
public:
virtual void Function( int ) = 0;
virtual int getBar(void) = 0;
};

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

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

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

extern "C" __declspec(dllexport) TestInterface *allocate_test() {
return new DllTest::Test();
}

最后,当您导入 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

关于c++ - 如何在命名空间中导入 C++ 类的 dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9296112/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com