[Solved] Referencing an object array in C# PInvoke


I finally found the solution to my problems, and am posting this for anyone who would need some clarification:

First, as David pointed out, simply treating the referenced argument as a pointer and assigning it the array’s address does not work. You have to copy the entire array contents into the referenced array. Easily fixed.

The second mistake was in the C# method signature; the descripton that was needed here was “[Out]”, with the brackets, compared to simply “out” (Once again, thanks David).

So, the end result:

The structs do not change, but the function signature in C# does:

[DllImport(@"Elemission.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void getResults([Out] intensityType[] graphData);

and here is a snippet of the function call:

int arraySize;
DllMethods.executeAcquisition(out arraySize); // arraySize is the Struct array length
intensityType[] resultData = new intensityType[arraySize];
DllMethods.getResults(resultData);

Meanwhile in C++, the C# call is received by the wrapper and passed to the member function…

__declspec(dllexport) void getResults(intensitytype* graphData)
{
    MainControl::getInstance()->getCamera()->getResults(graphData);
}

…and lo and behold, the struct array is filled.

void CameraControl::getResults(intensitytype* graphData)
{
    for (int i = 0; i < _spectroDataLength; i++)
        graphData[i] = _spectroData[i];
}

solved Referencing an object array in C# PInvoke