convert struct handle from managed into unmanaged C++/CLI

邮差的信 提交于 2019-12-03 03:47:09

Marshal::PtrToStructure does the opposite of what you want, it converts an unmanaged pointer to a managed object. You want Marshal::StructureToPtr.

Also, you would need to define an unmanaged class, because MyObject is a Managed Type. Assuming you have done that, you could do it like this (just converted this from the C# sample):

IntPtr pnt = Marshal::AllocHGlobal(Marshal::SizeOf(configObject)); 
Marshal.StructureToPtr(configObject, pnt, false);

You then have a pointer to the data, which you can memcpy or whatever into your native struct.

But MyObject is and will stay a managed type. If you want a truly unmanaged type, you have to define one that matches the managed struct.

Just wondering, why are you using unmanaged LPWSTR in a managed struct?

You probably mean:

struct MyUnmanagedStruct {
    LPWSTR var1, var2;
};

Then you can use Marshal.StructureToPtras suggested by Botz3000. Otherwise C#'s

public struct MyObject {
   public String var1;
   public String var2;
}

and C++/CLI's

public struct value MyObject {
   public String^ var1;
   public String^ var2;
}

are completely equivalent, assuming your're you're using the same System.String on both sides.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!