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

前端 未结 2 1505
生来不讨喜
生来不讨喜 2021-02-06 15:08

In C#, I defined a struct:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct MyObject
{
   [MarshalAs(UnmanagedType.LPWStr)]
   publ         


        
2条回答
  •  余生分开走
    2021-02-06 16:07

    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?

提交回复
热议问题