gpt4 book ai didi

c++ - 如何使用 dll 将 C++ 类库导出到 C#?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:18 28 4
gpt4 key购买 nike

在我之前的修订版游戏引擎中,我为 C# 的游戏编辑器移除了主要功能。现在,我开始用静态库修改游戏引擎。已经有一个用 C++ 创建的动态库来使用 DLLEXPORT for C#。刚才我想测试新功能并从 C++ 创建一个 DLL 文件。因为 DLL 包含类,所以我想知道如何才能使用 DLL 导出。我会这样做吗:

[DLLEXPORT("GameEngine.dll", EntryPoint="SomeClass", Conventional=_stdcall)]
static extern void functionFromClass();

我感觉它可能是 DLLImport 而不是 DLLExport。我想知道我该怎么做?我考虑的另一种方式是因为我已经准备好 C++ 中的 DLL 以进入 C# 类库。我可以将新引擎保留为一个库,并将该库与旧的 DLL C++ 文件链接起来。

难道 EntryPoint 不能指向函数所在的类吗?

最佳答案

您实际上不能像这样直接导出 C++ 类。

static extern void functionFromClass();

C++ 的问题在于它没有通用定义的 ABI(应用程序二进制接口(interface))。所以为了让其他语言理解你的 C++ 库 ABI,你需要用 C 函数包装它(几乎所有其他语言都理解 C)。

C 的问题在于它不理解类。另一方面,C++ 对象需要将 this 指针作为参数传递给它们的成员函数。所以为了用 C 接口(interface)包装你的 C++ 类。您需要显式处理传递的 this 参数,还需要定义类似于构造函数和析构函数的函数。

你需要这样做:

//Header File Foo.h
struct Foo; // Forward Declaration Only
Foo* createFoo( /* parameters */ );
void destroyFoo( Foo* obj );
int Func( Foo* obj, int i ); // obj should take this pointer
float Func2( Foo* obj, float i, float j );

这样实现

#include "Foo.h"
extern "C"
{
Foo* createFoo( const char * s )
{
return reinterpret_cast<Foo*>( new Foo( s ) );
}
void destroyFoo( Foo* obj )
{
delete reinterpret_cast<Foo*>(obj );
}
int Func( Foo* obj, int i )
{
return reinterpret_cast<Foo*>(obj)->Func(i);
}
}

最后,您可以将导出的 C 函数包装在 C# 类中,这样事情就回到了传统的面向对象的方式。

请注意,我什至没有提到继承或多态性。

关于c++ - 如何使用 dll 将 C++ 类库导出到 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935245/

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