Question

I have the following C++ function exported in a DLL:

extern "C" __declspec(dllexport) bool GetResolutionArray(int32_t adapterIndex, int32_t outputIndex, uint32_t arrayLength, Resolution outResolutionArr[]) {
        memcpy_s(
        outResolutionArr, 
        sizeof(Resolution) * arrayLength,
        RENDER_COMPONENT.GetResolutionArray(adapterIndex, outputIndex),
        RENDER_COMPONENT.GetOutput(adapterIndex, outputIndex).NumResolutions * sizeof(Resolution)
        );
    return true;
}

And, the matching extern function declaration in C#:

[DllImport(InteropUtils.RUNTIME_DLL, EntryPoint = "GetResolutionArray", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool _GetResolutionArray(int adapterIndex, int outputIndex, uint resolutionArrayLength, [MarshalAs(UnmanagedType.LPArray), In, Out] ref Resolution[] resolutions);

However, when I attempt to use this function as below, the program crashes with a FatalExecutionEngineError (indicating I corrupted something somewhere I guess) (error code 0xc0000005, i.e. access violation):

Resolution[] resolutions = new Resolution[outOutputDesc.NumResolutions];
if (!_GetResolutionArray(outAdapterDesc.AdapterIndex, outOutputDesc.OutputIndex, (uint) resolutions.Length, ref resolutions)) {
    EnginePipeline.TerminateWithError("Internal engine call failed: _GetResolutionArray");
}

I strongly suspect that my call to memcpy_s is causing the access violation, but I can't see how or why, and I therefore reason that perhaps the marshalling is going wrong somewhere.

Thank you.

Was it helpful?

Solution

The array parameter is declared incorrectly. A C# array is already a reference and so you don't need the ref. Declare it like this:

[DllImport(InteropUtils.RUNTIME_DLL, EntryPoint = "GetResolutionArray", 
    CallingConvention = CallingConvention.Cdecl)]
internal static extern bool _GetResolutionArray(int adapterIndex, 
    int outputIndex, uint resolutionArrayLength, Resolution[] resolutions);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top