How do I pass a pointer to an unknown struct from C++ to C# and back again?

67 views Asked by At

I'm working on integrating parts of another company's software with my company's software by using their provided SDK that has native DLLs with various functions that I need to use. Included with the SDK were example files written in C, which I've adapted so that I can call them from C# (the language our company's software is written in). I've done this by compiling a C++ DLL which I added to the C# project as a link.

This works for functions that return strings or ints. My problem is that I need to return a pointer to an unknown struct from my compiled DLL to my C# code, and back.

Here's some rough code snippets that show what I'm doing.

C++, compiled to MyDLL.dll:

extern "C" {
    __declspec(dllexport) customStruct* foo();
    __declspec(dllexport) int bar(customStruct*);
}

customStruct* foo() {
    // call SDK library function to return the pointer
}

int bar (customStruct* ptr){
    // do some things to the struct pointed to by the pointer
    // by passing it to various SDK library functions
}

C# (I'm aware marshalling/declaring the pointer needs to happen differently, but not how):

public partial class MyWindow : Window
{
    public MyWindow()
    {
        InitializeComponent();
    }

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        customStruct* ptr = foo();
        if (someCondition)
        {
            bar(ptr);
        }
    }

    [DllImport]("MyDLL.dll")
    private static extern customStruct* foo();

    [DllImport]("MyDLL.dll")
    private static extern int bar(customStruct* ptr);
}

I don't know the structure or contents of the struct the pointer points to, nor do I need to use them. The struct definition is hidden inside the provided libraries, and the only thing I'm doing with it is passing it into library functions that do unknown modifications to it. I'm not doing anything with the pointer in C#, but I need to pass it back and forth for control flow reasons. How exactly do I do this?

Thanks in advance.

0

There are 0 answers