1:新建c++模板,生成类型动态库
2:c++里类型
点击查看代码
class A
{
public:
int a;
};
typedef struct
{
int up;
int down;
char infos[4];
//LPWSTR infos;
}info,*LPinfo;
点击查看代码
#define CVAPI extern "C" __declspec(dllexport)
CVAPI int Add1(int a,int b ,int len);
对应c#
[DllImport(Dllpath, CallingConvention = CallingConvention.StdCall)]
public static extern int Add1(int a,int b ,int len);
点击查看代码
//定义函数模型
int _declspec(dllexport)_stdcall FuncCsharp(int*);
回调
int CallBackAdd(int a, intptr_t callBack)
{
decltype(FuncCsharp)* callHander = NULL;
if (callBack != 0)
{
callHander = (decltype(FuncCsharp)*)callBack;
}
int b = 6;
if (callHander != NULL)
{
b = callHander(&a);
}
return b;
}
c#使用
[DllImport(Dllpath, CallingConvention = CallingConvention.StdCall)]
public static extern int CallBackAdd(int a, IntPtr strPtr);
public delegate int CsharpCall(ref int a);
CsharpCall c = new CsharpCall(CsharpMethod);
IntPtr ptr = Marshal.GetFunctionPointerForDelegate(c);
var p2 = ptr.ToPointer();
var val=CallBackAdd(5, ptr);
5 基础数据类型对应
点击查看代码
c# c++
int,short,byte,long int,short,byte,long
ref int,short,byte,long int*,short*,byte*,long*
结构体c#里是托管类型,在封送时需要注意以下特性
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public static extern int StringToChar([MarshalAs(UnmanagedType.LPStr)] string str);