Convert structure descriptor from managed to unmanaged C ++ / CLI

In C #, I defined a struct:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct MyObject { [MarshalAs(UnmanagedType.LPWStr)] public string var1; [MarshalAs(UnmanagedType.LPWStr)] public string var2; }; 

I have this structure in C ++:

 public value struct MyObject { LPWSTR var1; LPWSTR var2; }; 

And in the C ++ method, which is a public class that is called from C #:

 TestingObject(MyObject^ configObject) { // convert configObject from managed to unmanaged. } 

The object is being debugged correctly, that I see two lines var1 and var2. However, now the problem is that I need to marshal the object: configObject into an unmanaged object.

What I think of doing something like this:

 TestingObject(MyObject^ configObject) { // convert configObject from managed to unmanaged. MyObject unmanagedObj = (MyObject)Marshal::PtrToStructure(configObject, MyObject); } 

This is something I can think of, but not in the know, I got this error:

Error 2 error C2275: "MyObject": illegal use of this type as an expression

Is it right to convert a managed object to an unmanaged object? If so, how can I do this Marshal::PtrToStructure correctly? If not, how can I do this?

+4
source share
2 answers

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

In addition, you will need to define an unmanaged class because MyObject is a managed type. Assuming you did this, you can do it like this (just change this from a C # sample):

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

Then you have a pointer to the data you can memcpy or something in your own structure.

But MyObject will remain a managed type. If you want a truly unmanaged type, you must define one that matches the managed structure.

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

+2
source

You probably mean:

 struct MyUnmanagedStruct { LPWSTR var1, var2; }; 

Then you can use Marshal.StructureToPtr , as suggested by Botz3000. Otherwise c #

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

and C ++ / CLI

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

fully equivalent if you use the same System.String on both sides.

+1
source

Source: https://habr.com/ru/post/1403093/


All Articles