PInvoke互操作技术
- c++编写
--- Person.cpp
extern "C"
{
_declspec(dllexport) int Sum(int a, int b);
}
--- Person.h
#include "Person.h"
#include "iostream"
using namespace std;
int Sum(int a, int b)
{
return a + b;
}
- c#调用
class Program
{
[DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int Sum(int a, int b);
static void Main(string[] args)
{
var result = Sum(10, 20);
Console.WriteLine($"10+20={result}");
Console.ReadLine();
}
}
---- output -----
10+20=30
- c#编写,c++调用
--- main.cs
class Program
{
delegate void Callback(int a);
[DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl)]
extern static void AsyncProcess(Callback callback);
static void Main(string[] args)
{
AsyncProcess((i) =>
{
//这里回调函数哦...
Console.WriteLine($"这是回调函数哦: {i}");
});
Console.ReadLine();
}
}
------- output -------
这是回调函数哦: 10
--- Person.cpp
extern "C"
{
//函数指针
typedef void(_stdcall* PCALLBACK) (int result);
_declspec(dllexport) void AsyncProcess(PCALLBACK ptr);
}
--- Person.h
#include "Person.h"
#include "iostream"
using namespace std;
void AsyncProcess(PCALLBACK ptr)
{
ptr(10); //回调C#的委托
}
环境配置
- 用vs2019创建C++的Console App,修改两个配置: 将程序导出为dll,修改成compile方式为Compile as C++ Code (/TP)