Marshal.PtrToStructure(),struct包含双指针menebre(映射到IntPtr)

时间:2013-05-03 00:10:51

标签: c# .net marshalling intptr

我正在动态加载win32 DLL并调用一个函数。该函数包含一个pass-by-ref参数,该参数是一个包含双指针作为成员的struct。我将双指针成员编组为IntPtr,然后将struct参数编组为IntPtr。这部分代码似乎没问题。

在函数调用(MethodInfo.Invoke())之后,我使用Marshal.PtrToStructure()从IntPtr获取返回的struct数据并获得异常"Cannot evaluate expression because the code of the current method is optimized."。我确保该项目未选中“优化代码”。

以下是简化代码:

typedef struct {
    int x;
    int** xx;
}Struct_DoubPtr
int PassOutDoubPtrStructMember(Struct_DoubPtr* ptrStructMember);

marshal struct to IntPtr:

var obj = Activator.CreateInstance(Type.GetType("Struct_DoubPtr"));
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj));

在调用Marshal.StructureToPtr(obj,ptr,false)之前,使用成员x = 20和xx = IntPtr初始化“obj”;

Marshal IntPtr to struct:

Type type = Type.GetType("Struct_DoubPtr");
var newObj = Activator.CreateInstance(type);
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo field in fields)
{   
    //if the field is an IntPtr 
    //a seperate function iscalled here to determine if the memeber is a IntPtr
    {   
        field.SetValue(newObj, IntPtr.Zero);
    }
}
Marshal.PtrToStructure(dataPtr, newObj); 
//where dataPtr is the strcut parameter from invoking PassOutDoubPtrStructMembe()

任何意见/建议都将是一个很大的帮助。

0 个答案:

没有答案