Jump to content
  • Advertisement
Sign in to follow this  
Sphet

[.net] Passing vertex data from C# to native API.

This topic is 3772 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

Still getting up to speed on all this .NET, C# and CLI/C++ stuff. I have a native function that takes an array of vertices and renders them: void RenderVertices( VertexPC* pVertices, int numVertices ); The vertex structure is defined like this: struct VertexPC { Vector3 position; DWORD colour; }; Now, I want to be able to create an array of vertices in my C# application, and pass it to the RenderVertices in my CLI/C++ layer. Does C# guarantee fixed structure sizes for value types that I can just pin and pass to a C++ function? Can I just define a C# structure with the same members and cast it to the native type after pinning? Regards, S.

Share this post


Link to post
Share on other sites
Advertisement
Quote:

Does C# guarantee fixed structure sizes for value types that I can just pin and pass to a C++ function? Can I just define a C# structure with the same members and cast it to the native type after pinning?

No and no; more importantly, C# doesn't guarantee structure layouts. The runtime is free to lay a class or struct out in memory however it likes. You need to define the struct layout explicitly via the StructLayoutAttribute before the suitable pinning tricks can be guaranteed (LayoutKind.Sequential is generally suitable).

Share this post


Link to post
Share on other sites
Here's an example of your desired C++/CLI RenderVertices function. I'm assuming you are using the C++/CLI application as a glue layer between a C# program and a C++ DLL.


[StructLayout(LayoutKind.Sequential)]
public value class ManagedVertex
{
public:
int X;
int Y;
};

struct NATIVE_VERTEX
{
int X;
int Y;
}

void RenderVertices(array<ManagedVertex>^ vertices)
{
pin_ptr<ManagedVertex> pinnedVertices = &vertices[0];

MyNativeRenderVertices(reinterpret_cast<NATIVE_VERTEX*>(pinnedVertices));
}



Of course, you need to be sure that you declare your managed vertex appropriately to ensure that each member is the correct size and in the right order, otherwise strange and amazing things will occur with your memory [smile]

Share this post


Link to post
Share on other sites
Thanks for the replies from both of you. I'd assumed that there was some special requirements here.

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!