Sign in to follow this  

[.net] native struct to managed

This topic is 3315 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am mixing C++/CLI and C#. The C++/CLI library has a class that generates an instance of a native struct and wants to return a managed version of it, so that the C# assembly can use it. Say the types are: struct VECTOR { float x; float y; float z; }; value struct Vector { float x; float y; float z; }; Is there an easy way to do this: VECTOR v = ...; Vector u = v; How can I construct a Vector from a VECTOR without manually copying each element over? Is there some .NET helper method that will just do a byte copy?

Share this post


Link to post
Share on other sites
You will have to marshal it across. Take a look at Marshal.PtrToStructure(). Also you will have to make your managed struct "Sequential" ([StructLayout(LayoutKind.Sequential)]). Pass a pointer to your unmanaged struct using a pointer and IntPtr on the C# side. Don't forget to free up the IntPtr afterwards using Marshal.FreeHGlobal().

Share this post


Link to post
Share on other sites
Quote:
Original post by Mike.Popoloski
You can pin the managed structure and then just fill it with a memcpy, assuming the two layouts are the same. As Headkaze said, make sure you mark your managed structure with the StructLayotu attribute.


Just nitpicking here, but LayoutKind.Sequential is the default for managed structs (not for classes). Most declare it anyway (I know I do), but it's not actually necessary.

Edit: Another caveat to be aware of is that there is no ordering guarantee for C# default properties, i.e:

[StructLayout(LayoutKind.Sequential)]
struct Foo
{
float X { get; set; }
float Y { get; set; }
}



The compiler is free to order the backing fields however it likes (relevant connect issue).

Share this post


Link to post
Share on other sites

This topic is 3315 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this