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?

There’s a detailed and fairly readable reference in MSDN here: Marshalling Classes, Structures, and Unions - .NET Framework | Microsoft Learn

“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.