PInvoke用于在应用启动时将以下结构从VB.net传递到非托管C。当我单步执行代码时,所有值都会正确传递。在被调用的C方法中,我将ptr保存到传入的struct。
<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;
}
将ptr保存到传入的struct后,只要函数返回VB.net,ptr就会无效。
我怀疑在回调函数返回后释放了编组器分配的内存
有没有办法告诉编组人员在编组时不释放它分配的内存?
感谢任何评论。 感谢
答案 0 :(得分:0)
p / invoke封送程序传递给非托管代码的指针仅在非托管函数返回之前有效。我有两种选择:
IntPtr
。并致电Marshal.AllocHGlobal
和Marshal.StructureToPtr
。 后一种选择更常被选择。