C#調用c++兩種方式,一種是在同一個解決方案中建兩個工程,一個是c#上位機,一個是c++程序,另一種方式是只生成包含c#上位機的解決方案,調用c++生成的DLL文件。
【本文內容大部分借鑒https://blog.csdn.net/qq21497936/article/details/83825098 和 https://blog.csdn.net/ghevinn/article/details/17297685 ,方便自己以后使用簡單做了總結。】
第一種方式,解決方案中包含兩個工程。
一、建立C庫
1.建立Visual C++ Dll空項目
打開VS2019建立Visual C++桌面向導,如下圖:
點擊確認后,開始向導創建工程,如下圖:
2.創建庫源碼,生成C庫
添加頭文件(cDllDemo.h)與源文件(cDllDemo.cpp)
編輯頭文件,定義變量和函數宏定義:
#pragma once extern int index = 99; extern float array0[5] = {0,1,2,3,4}; extern "C" _declspec(dllexport) int testDll(); extern "C" _declspec(dllexport) int add(int a, int b); extern "C" _declspec(dllexport) int sub(int a, int b); extern "C" _declspec(dllexport) void return_array(float* array1);
__declspec(dllexport)用於Windows中的動態庫中,聲明導出函數、類、對象等供外面調用,省略給出.def文件。即將函數、類等聲明為導出函數,供其它程序調用,作為動態庫的對外接口函數、類等。
編輯源文件,實現函數源碼:
#include "cDLLDemo.h" int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } //返回值 int testDll() { return index; } //返回一維數組值 void return_array(float* array1) { for (int i =0;i<5;i++) { array1[i] = array0[i]; } }
編譯生成動態庫:
Debug文件中生成的dll文件:
3.回調函數
(1) C#向c++傳遞一維數組
//返回一維數組值 void return_array(float* array1) { for (int i =0;i<5;i++) { array1[i] = array0[i]; } }
(2)C#向c++傳遞單個值
//返回值 int testDll() { return index; }
二、Winform使用C庫
- 建立winform工程
2.設置依賴項,為了每次運行該測試應用之前,先編譯生成對應的dll,方式dll修改未更新,如下圖:
3.使用C庫中的全局變量
[DllImport(@"D:\calligraphy\demo\cDLLdemo\Debug\cDLLdemo.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int testDll(); [DllImport(@"D:\calligraphy\demo\cDLLdemo\Debug\cDLLdemo.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int add(int a, int b); [DllImport(@"D:\calligraphy\demo\cDLLdemo\Debug\cDLLdemo.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int sub(int a, int b); [DllImport(@"D:\calligraphy\demo\cDLLdemo\Debug\cDLLdemo.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void return_array(float[]array1);
4.使用C庫中的回調函數
float[] array2 = new float[5]; public Form1() { InitializeComponent(); int a = 2; int b = 3; //調用c庫中的add函數和sub函數 MessageBox.Show(add(a, b) + ""); MessageBox.Show(sub(a, b) + ""); //調用C庫中的回調函數 return_array(array2); }
5.運行程序:
把c#工程設置為啟動項目
設置C++工程的屬性,平台改為win32。設置c#工程的屬性,目標平台改為x86.
運行程序,add(2,3) 結果為5,sub(2,3)結果為-1
得到了C++工程中數組arra0的值{0,1,2,3,4}
.
第二種方式是在C#中調用c++DLL.
一、生成C庫
1.創建 動態鏈接庫,添加頭文件和源文件與第一種方式相同,編譯生成DLL文件
二、將DLL文件放在c#工程的bin debug文件中,其他步驟與第一種相同