Using C++/CLI structs from C#

Viewed 3813

Let me start another question because although I saw many similar ones, not one really speaks about this aspect... I have a C++ DLL (no source code but .lib and .h) and I wrote the necessary managed wrapper. There is no problem with that, the question is about the structs and enums defined in the original C++ code, and there are lots of them, all needed to be exposed to the C# code. Tutorials and samples usually use simple data types like floats and strings, not real world scenarios of complex data structures.

My managed C++/CLI wrapper consumes the unmanaged structs from the DLL's .h header files. The class member functions that I wrap use them all the time. Consequently, I need to use the same structs in my C# code, passing them and receiving from the C++ code. It seems clear that I can't avoid redefining all of them in C# but even then, using them is problematic. Let's have an example: a simple struct that is used by a function in the unmanaged code:

typedef struct INFO {
  ...
} INFO;

int GetInfo(INFO& out_Info);

I have the same structure declared in my C++/CLI wrapper code:

public ref struct INFO_WRAP {
  ...
};

int GetInfo(INFO_WRAP out_Info);

The implementation in the wrapper code tries to convert this new structure to the original one for the consumption of the old, unmanaged code:

int Namespace::Wrapper::GetInfo(INFO_WRAP out_Info) {
  pin_ptr<INFO> pin_out_Info = out_Info;
  return self->GetInfo(*(::INFO*)pin_out_Info);
}

But this won't compile (cannot convert between the structs and no suitable conversion is found).

Is there a solution that doesn't involve creating new data structures and manually copying all struct members all the time, back and forth? Not only because of the extra work and time, but there are really many structs.

2 Answers
Related