是否可以从 .NET 语言(如 C#)中调用可能编译为代码库文件 (.dll) 的 C++ 代码?
特别是 C++ 代码,例如 RakNet 网络库。
最佳答案
调用 C++ 的一种简单方法是在 C++/CLI 中创建包装程序集。在 C++/CLI 中,您可以像编写 native 代码一样调用非托管代码,但您可以从 C# 调用 C++/CLI 代码,就好像它是用 C# 编写的一样。该语言基本上被设计为与现有库的互操作,作为其“ killer 级应用”。
例如 - 使用/clr 开关编译它
#include "NativeType.h"
public ref class ManagedType
{
NativeType* NativePtr;
public:
ManagedType() : NativePtr(new NativeType()) {}
~ManagedType() { delete NativePtr; }
void ManagedMethod()
{ NativePtr->NativeMethod(); }
};
然后在 C# 中,添加对 ManagedType 程序集的引用,并像这样使用它:
ManagedType mt = new ManagedType();
mt.ManagedMethod();
查看 this blog post一个更解释的例子。
关于c# - 可以从 C# 调用 C++ 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/935664/