- Home /
Pass a struct from Unity to C++ library
Hello,
I'm using a C++ custom library I built for Unity in one of my projects. I'm sending a C# struct while invoking a method in the C++ library. These structs are using the exact same names and order in its members on both C++ and C# classes. But only some of the struct members are being received correctly on the C++ side. Others are going back to default value. I only have int and bool members in the struct. No arrays. Any idea what might be happening?
it might be helpful if you share the structure of your structs. At least one working one and one which fails.
Answer by Bunny83 · May 24 at 10:04 PM
Like Captain P. said, you should share your code. Keep in mind to use export "C"
on the C++ side to avoid name mangling.
On the managed C# side you have to use [StructLayout(LayoutKind.Sequential)]
on your struct to ensure a sequential memory layout.
Finally keep in mind that depending on the compiler and platform, in C++ the actual size of an int, long, etc can vary. So again, it would be way easier to provide a clear answer if we had your actual code as reference. If you want to provide the code, feel free to edit your question and add the relevant code snippets.
@Bunny83 Thank you for the response. I indeed needed to add the [StructLayout(LayoutKind.Sequential)] attribute to the struct. I also ended up having to use [MarshalAs(UnmanagedType.U1)] for all the bools and [MarshalAs(UnmanagedType.R4)] for floats inside the struct. This resolved my issue.
Your answer

Follow this Question
Related Questions
Using C++ DLL's from Unity's C#? 3 Answers
Android Music selection 3 Answers
Unity Library 1 Answer
How can I use Magick in Unity? 1 Answer
How to create a library from my C# project that runs on Android 1 Answer