【本文内容大部分借鉴https://blog.csdn.net/qq21497936/article/details/83825098 和 https://blog.csdn.net/ghevinn/article/details/17297685 ,方便自己以后使用简单做了总结。】
C#调用c++两种方式,一种是在同一个解决方案中建两个工程,一个是c#上位机,一个是c++程序,另一种方式是只生成包含c#上位机的解决方案,调用c++生成的DLL文件。
第一种方式,解决方案中包含两个工程。
一、建立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库
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文件中,其他步骤与第一种相同
原文:https://www.cnblogs.com/ICgj/p/14723108.html