C#呼叫C++動態連結庫(dll)的簡單樣例
阿新 • • 發佈:2021-09-01
環境:Win10、VS2017
一、生成C++動態連結庫dll
1. 建立動態連結庫dll
2. 新建一個C++類
3. 開啟FourArith.cpp檔案,新增四則運算方法
4. 生成解決方案,編譯生成dll
二、使用C#控制檯應用呼叫上述生成的.dll
1. 新建控制檯應用
2. 為了方便呼叫dll,把MyDll.dll複製到\bin\Debug目錄下。
3. 呼叫MyDll.dll的方法
1 [DllImport("MyDll.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]2 public static extern double Add(double a, double b); 3 [DllImport("MyDll.dll", EntryPoint = "Sub", CallingConvention = CallingConvention.Cdecl)] 4 public static extern double Sub(double a, double b); 5 [DllImport("MyDll.dll", EntryPoint = "Multi", CallingConvention = CallingConvention.Cdecl)]6 public static extern double Multi(double a, double b); 7 [DllImport("MyDll.dll", EntryPoint = "Divi", CallingConvention = CallingConvention.Cdecl)] 8 public static extern double Divi(double a, double b); 9 10 static void Main(string[] args) 11 { 12 doublea = 2; 13 double b = 3; 14 15 Console.WriteLine(Add(a, b)); 16 Console.WriteLine(Sub(a, b)); 17 Console.WriteLine(Multi(a, b)); 18 Console.WriteLine(Divi(a, b)); 19 Console.ReadKey(); 20 }
4. 執行檢視效果