Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] native struct to managed

Started by Quat Nov 16, 2008 at 3:59 PM 2 replies 2.2k views
Original Post
Quat
Quat
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?
-----Quat
Headkaze
Headkaze
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().
Mike.Popoloski
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.
Mike Popoloski | Journal | SlimDX
Fiddler
Fiddler
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).
[OpenTK: C# OpenGL 4.4, OpenGL ES 3.0 and OpenAL 1.1. Now with Linux/KMS support!]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.