- Home /
iOS Plugin - Pass a struct from C++ to C#
I need to pass a struct from C++ to C#, and I'm not sure where to begin.
I am more familiar with Unity / C# than Xcode / c++.
I have found some answers that mention "Marshaling", but the info is over my head, and I can't seem to find a simple example.
In C++ I have this struct:
extern "C"
{
typedef struct StructName {
void* valueA;
int valueB;
int valueC;
float valueD[4];
int valueE;
int valueF;
int valueG;
uint64_t valueH;
float valueI[6];
} StructName;
}
extern "C" StructName GetStruct() {
return structVariable;
}
From C# I would like to call the above GetStruct method and be able to access the properties of it. How would I do this?
Answer by Baroque · Jan 05, 2017 at 08:40 PM
There's a detailed and fairly readable reference in MSDN here: https://msdn.microsoft.com/en-us/library/eshywdt7(v=vs.110).aspx
"Marshalling" simply means converting data from native code (i.e. raw memory) to managed code (i.e. Mono, in Unity's case), or vice-versa.
If your structure contains simple types (floats, integers, etc.) then it's often as simple as creating the same structure in C# and adding [StructLayout(LayoutKind.Sequential)]
above it. Surprisingly enough this is even smart enough to automatically marshal strings from a null-terminated char *
to a c# string
.
For float valueI[6]
in your example you need to tell C#/Mono how that array is represented in memory using [MarshalAs(UnmanagedType.R4, SizeConst=6]
above that element.
Where this gets more complicated is with references to other classes, or especially void *
. You can represent pointers in C# using the type System.IntPtr
and safely pass them around but you can't directly do anything with them. You will have to do your own reading if you need to pass complex types around.
You pretty much covered everything one could say about that topic, well done.
+1