C++ 定义
typedef struct Stu
{
public:
int Age;
char Name[20];
};
typedef struct Num
{
int N1;
int N2;
};
extern "C" __declspec(dllexport) void FindInfo(Stu& stu)
{
stu.Age = 10;
strcpy_s(stu.Name, "徐滔");
}
extern "C" __declspec(dllexport) int Add(int a,int b)
{
return a + b;
}
extern "C" __declspec(dllexport) int GetNumSum(Num* num)
{
return num->N1 + num->N2;
}
在C# 中需要重新定义结构
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Stu
{
public int Age;
[System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValTStr,SizeConst =20)]
public string Name;
}
注意c# 中 和c++ 中的数据类型的对应。
public struct Num
{
public int N1;
public int N2;
}
申明 调用函数
[DllImport("MyFuncDll.dll", EntryPoint = "FindInfo", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode)]
extern static void FindInfo(ref Stu stu);
[DllImport("MyFuncDll.dll", EntryPoint = "Add", CallingConvention = CallingConvention.Cdecl)]
public extern static int Add(int a, int b);
[DllImport("MyFuncDll.dll", EntryPoint = "GetNumSum", CallingConvention = CallingConvention.Cdecl)]
public extern static int GetNumSum(ref Num num);
调用测试
int re = Add(1, 3);
Num n = new Num() { N1 = 1, N2 = 2 };
int r = GetNumSum(ref n);
Stu stu = new UseCppDll.Stu();
FindInfo(ref stu);
MessageBox.Show(stu.Name);