Struct PInvoke:CLR封送器分配的内存何时释放?
PInvoke用于在应用程序启动时将以下结构从VB.net传递到非托管C。当我逐步完成代码时,所有的值都被正确地传入。在被调用的C方法中,我将ptr保存到传入的结构中Struct PInvoke:CLR封送器分配的内存何时释放?,struct,pinvoke,unmanaged-memory,Struct,Pinvoke,Unmanaged Memory,PInvoke用于在应用程序启动时将以下结构从VB.net传递到非托管C。当我逐步完成代码时,所有的值都被正确地传入。在被调用的C方法中,我将ptr保存到传入的结构中 <StructLayout(LayoutKind.Sequential)> Structure teststruct <MarshalAs(UnmanagedType.I2)> Public TestData As Short <MarshalAs(UnmanagedType.I2)&
<StructLayout(LayoutKind.Sequential)>
Structure teststruct
<MarshalAs(UnmanagedType.I2)> Public TestData As Short
<MarshalAs(UnmanagedType.I2)> Public TestData2 As Short
<MarshalAs(UnmanagedType.I2)> Public TestData3 As Short
<MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.I2, SizeConst:=256)> Public TestData4() As Short
End Structure
//Matching C struct
struct teststruct
{
short TestData;
short TestData2;
short TestData3;
short TestData4[256];
};
//The method in C that saves ptr to the struct that is passed in (Worked with VB6)
struct teststruct *VCstruct;
void DllCallbackFunc(struct teststruct *VBStruct)
{
VCstruct = VBStruct;
}
结构测试结构
公共测试数据短
公共测试数据2简称
公共测试数据3简称
Public TestData4()短为
端部结构
//匹配C结构
结构测试结构
{
短测试数据;
短测试数据2;
短测试数据3;
短测试数据4[256];
};
//C语言中将ptr保存到传入的结构的方法(使用VB6)
struct teststruct*VCstruct;
void DllCallbackFunc(结构teststruct*VBStruct)
{
VCstruct=VBStruct;
}
在我将ptr保存到传入的结构之后,一旦函数返回到VB.net,ptr就会无效
我怀疑marshaller分配的内存在回调函数返回后被释放
有没有办法告诉封送处理程序不要释放在封送处理期间分配的内存
感谢您的评论。
谢谢p/invoke封送拆收器传递给非托管代码的指针仅在非托管函数返回之前有效。在我看来,你有两个选择:
IntPtr
。并调用Marshal.AllocHGlobal
和Marshal.StructureToPtr
李>
后一种选择更为常见 这是不可能的。这里没有神奇的解决方案,你必须自己分配内存。将config参数声明为IntPtr,而不是ref config。使用Marshal.SizeOf、Marshal.AllocHGlobal和Marshal.StructureToPtr。