Search code examples
c#c++pointersstructinterop

How do you extract data from a C++ library to a struct pointer in C#


I have a third party library and their C# wrapper was just a minimal list of DLLImport from their C++ library. There is a method I am trying to use that is passing data like this

public static extern ErrorResult GetData(void* pData)

I know the data is a struct, and they do provide the struct with the StructLayout attributes to make it explicit in size similar to below

[StructLayout(LayoutKind.Explicit, Size = 120)]
unsafe public struct DataStruct
{
    //stuff
}

I'm trying to do this

unsafe
{
    DataStruct* data;
    var error = Wrapper.GetData(data);
}

but this errors saying that data is unassigned CS0165 use of unassigned local variable 'data'

I tried to initialize data, and I found this question, but the answer just says don't do this in C#, but I don't have control over the third party API that I'm using and need to extract the data how they have it set up and documentation and examples are sparse.

Others on that question suggested stackalloc, but I'm not sure what what that would look like in the case of a struct.


Solution

  • I was able to test with the hardware I am working with, and I can confirm that changing the wrapper signature to be the below does work.

    public static extern ErrorResult GetData(ref DataStruct data)
    

    In my scenario the type of struct returned can change, but that's also an easy fix as overloads can be added for the different struct types supported

    public static extern ErrorResult GetData(ref DifferentDataStruct data)