C# 調用 C++ DLL 可直接用 DllImport,但 C++ 調用 C# DLL 需啟用公共語言運行庫 (CLR) 支持。
namespace Csharp {
public class Class1 {
public string Name = string.Empty;
public Class1() { Name = "We can use C#!!"; }
}
}
編譯生成 Csharp.dll。
/clr。#include "stdafx.h"
#using "Csharp.dll"
using namespace Csharp;
int _tmain(int argc, _TCHAR* argv[]) {
Class1 ^a = gcnew Class1(); // 托管對象用 ^,分配用 gcnew
printf("%s\n", a->Name);
return 0;
}
關鍵點: 托管類型使用 ^ 控制代碼,內存由 GC 管理,需用 gcnew 分配。

由此實現 C++ 與 C# 互操作。