專案核心演算法需防反編譯,決定以 C++ 實作核心邏輯編譯為 DLL,C# 負責 UI 與資料存取,透過 P/Invoke 調用。
CppDemo.cpp 實作導出函式:
extern "C" __declspec(dllexport) int Add(int a, int b)
{
return a + b;
}
CppDemo.dll。InteropDemo。System.Runtime.InteropServices。DllImport 靜態導入:
using System;
using System.Runtime.InteropServices;
namespace InteropDemo
{
class Program
{
[DllImport("CppDemo.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
static void Main(string[] args)
{
Console.WriteLine(Add(1, 2)); // 輸出 3
Console.Read();
}
}
}
extern "C":防止 C++ 名稱修飾,確保導出名稱即為 Add。CallingConvention.Cdecl:符合 C++ 預設呼叫慣例。CppDemo.dll 放置於 C# 專案輸出目錄 (bin/Debug) 或系統 PATH 路徑。