- Home /
Objective-C Plugin - Arrays
I would like to pass an array of structs from C# to C over the plug-in bridge.
I already have methods working perfectly where I pass primitive values, and also a method where I pass a struct back and forth.
I have searched the Unity Forum and UnityAnswers to see how one would pass an array back but have not found anything for C/Obj-C.
Just looking for a really simple example.
Thanks
Answer by fhmiv · Jan 07, 2010 at 03:17 PM
System.Collections.ArrayList probably won't pass over the bridge, since it's a .NET class, and C/Obj-C won't know how to interpret it. If you want or need to use this type of array for some other reason, you can take the approach used in the Midi Plugin Example, and reconstruct the ArrayList/NSArray on each side of the bridge by passing each element one at a time and add()ing it.
Your other choice is to use fixed-sized arrays, which are just pointers to the first element in declared like this in C#:
[DllImport ("PluginName")] private static extern int FooPluginFunction(ref YourStruct[] aStruct);
int[] arrayOfInts = { 0, 1, 2, 3 }; // One way to declare it YourStruct[2] arrayOfYourStructs;
arrayOfYourStructs[0] = yourStruct; arrayOfYourStructs[1] = anotherYourStruct; // Declare it with fixed size and assign to it later FooPluginFunction(ref arrayOfYourStructs);
And on the C++ side:
int FooPluginFunction(YourStruct* &inStruct)
{
inStruct[0].whatever = whatever;
return someResult;
}
I will give the fixed-size array a try. I have a variable number of items to move across the bridge, I just wanted to avoid paying the bridging overhead for each item. This method gives me a way to batch in 5's or 10's as appropriate and reduce the bridging overhead.
Thanks for this!!
For this to work, you just have to make sure to pass an array of structs, not of classes, as structs store the actual data in the array. Also, you will probably want to pass the size of the array to C++ in another parameter, as you will not be able to get that from the array otherwise.
Here's a formatted version of the code (don't understand how it would work since I don't see how you transfer the definition of YourStruct between C# and C++):
C#
[DllImport("PluginName")]
private static extern int FooPluginFunction(ref YourStruct[] aStruct);
void Test()
{
int[] arrayOfInts = { 0, 1, 2, 3 }; // One way to declare it
YourStruct[2] arrayOfYourStructs;
arrayOfYourStructs[0] = yourStruct;
arrayOfYourStructs[1] = anotherYourStruct; // Declare it with fixed size and assign to it later
FooPluginFunction(ref arrayOfYourStructs);
}
C++
int FooPluginFunction(YourStruct* &inStruct)
{
inStruct[0].whatever = whatever;
return someResult;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613194218im_/https://answers.unity.com/themes/thub/images/avi.jpg)