Jump to content
  • Advertisement
Sign in to follow this  
Quat

[.net] native struct to managed

This topic is 3623 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
Advertisement
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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!