互操作有兩條路徑:C++ 調用 .NET 框架,或 .NET 調用 C++。本文從最簡單的場景切入,逐步建立完整認知。
只需引入兩個組件並用 `/clr` 編譯:
#using <mscorlib.dll>
#using <System.dll>
using namespace System;
void main() {
Console::WriteLine("Hello, world");
}
編譯:`cl /clr hello.cpp`
托管物件可像原生 C++ 類一樣用 `new` 創建、指標語法訪問:
DateTime d = DateTime::Now;
String* s = String::Format("The date is {0}\n", d.ToString());
Console::WriteLine(s);
Console::WriteLine(s->Length);
將外部函數聲明為類的靜態成員,用 `DllImport` 指定 DLL:
public class Win32 {
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, int type);
}
// 調用
Win32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0);
讀者 Giuseppe 遇到 `Run-Time Error Check Failure #0`,原因是 C# 用 `StdCall` 調用 C++ 的 `ThisCall` 函數。解決方案:編寫托管包裝器而非直接 P/Invoke 成員函數。