c++ 类型是非拖管的,需要做封送处理,才可以在c#中使用
详细介绍见:https://blog.csdn.net/sgzwiz/article/details/40980771
举个例子,
在c++库中定义一个结构体,一个接口函数bool Func(MyStruct* temp),并将其导出,导出方式见博文:https://mp.csdn.net/console/editor/html/105665917
struct MyStruct
{
int* _pBuff;
int num;
};
bool Func(MyStruct* temp)
{
temp->_pBuff = 0;
temp->num = 10;
}
在C# 中定义如下
开辟的字节大小根据类型定义的不同而不同,注意需要选择正确的字节大小。
[Serializable]
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MyStruct
{
[MarshalAs(UnmanagedType.SysInt)]
public IntPtr _pBuff;
[MarshalAs(UnmanagedType.I4)]
int num;
};
public class Base
{
[DllImport(@"***.dll", EntryPoint = "Func", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern unsafe bool Func(out IntPtr temp);
public static bool Func(ref MyStruct temp)
{
int size = Marshal.SizeOf(typeof(MyStruct));
IntPtr pBuff = Marshal.AllocHGlobal(size);
IntPtr p = new IntPtr(pBuff.ToInt64() + size);
Marshal.StructureToPtr(temp, p, false);
bool code = Base.Func(out pBuff);
Marshal.FreeHGlobal(pBuff);
return code;
}
}
MyStruct temp = new MyStruct();
bool rel = Base.Func(ref temp);