// MyLib.cpp
extern "C" __declspec(dllexport) int add(int a, int b) { return a + b; }
必須 加上 extern "C",否則導出名稱會被修飾(如 ?add@@YAHHH@Z),C# 無法以 "add" 找到入口點。
C:\> cl /LD MyLib.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804
... 生成 MyLib.dll, MyLib.lib, MyLib.obj, MyLib.exp
/LD 參數指示產生 DLL。
using System;
using System.Runtime.InteropServices;
public class InvokeDll
{
[DllImport("MyLib.dll", CharSet = CharSet.Auto)]
static extern int add(int a, int b);
public static void Main()
{
Console.WriteLine(add(10, 30)); // 輸出 40
}
}
DllImport 屬性指定 DLL 名稱與字元集,static extern 宣告外部方法簽章,呼叫方式如同一般靜態方法。