调用C++的一种简单方法是在C++/CLI中创建包装程序集.在C++/CLI中,您可以像编写本机代码一样调入非托管代码,但是可以从C#调入C++/CLI代码,就像它是用C#编写的一样.该语言的设计基本上是将与现有库的互操作作为其"杀手级应用程序".
例如-使用/clrswitch 编译此命令
#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了解更多解释的示例.