首先我们介绍一下原理:
C#与C++的转换会经过以下几层转换
1. C# APP
2. C#接口类:C#数据 -> 纯C数据结果包装
3. C接口包装:纯C数据 -> C++输入
4. C++实现:C++处理
接下来我们介绍一下具体实现方法:
首先建立一个C#项目
文件--添加新建项目--Win32 控制台应用程序--AdderImpl
源文件--右键添加cpp文件
[cpp] view plain copy print ? // the code is write in c #ifdef __cplusplus extern "C"{ #endif __declspec(dllexport) int __cdecl add(int a, int b); #ifdef __cplusplus } #endif int add(int a, int b) { return a + b; } // the code is write in c #ifdef __cplusplus extern "C"{ #endif __declspec(dllexport) int __cdecl add(int a, int b); #ifdef __cplusplus } #endif int add(int a, int b) { return a + b; }AdderImpl项目修改配置类型为动态库(.dll)
AdderImpl右键--生成
把该dll文件复制到
在testApp2右键--添加新建项--C#类--AdderWapper.cs
其中AdderWapper.cs中代码为:
[csharp] view plain copy print ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace TestApp { class AdderWapper { [DllImport("AdderImpl.dll", CallingConvention = CallingConvention.Cdecl)] static extern private int add(int a, int b); static public int performAdd(int a, int b) { // convert c# data to c data // TODO: // call the c interface int ret = add(a, b); // convert result from c data to c# data // TODO: // return the result return ret; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace TestApp { class AdderWapper { [DllImport("AdderImpl.dll", CallingConvention = CallingConvention.Cdecl)] static extern private int add(int a, int b); static public int performAdd(int a, int b) { // convert c# data to c data // TODO: // call the c interface int ret = add(a, b); // convert result from c data to c# data // TODO: // return the result return ret; } } } Program.cs中代码为: [csharp] view plain copy print ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestApp { class Program { static void Main(string[] args) { int a = 3; int b = 5; int c = AdderWapper.performAdd(a, b); System.Console.WriteLine(c); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestApp { class Program { static void Main(string[] args) { int a = 3; int b = 5; int c = AdderWapper.performAdd(a, b); System.Console.WriteLine(c); } } } 生成,也就是让dll和exe在同一文件夹下
命令行运行exe文件
end
