Connecting c++ and c# code with a c++/cli bridge

2019-04-15 02:46发布

问题:

I have a client application in native c++ code which is using native c++ dlls. I am investigating the possibility of connecting this code with c# dlls as they would be much easier to write. I decided to write a c++/cli bridge dll which can be loaded with LoadLibrary and which would pass the calls to c# dll.

The communication between the client and the dll is such that the client passes a pointer to an interface object through which the dll then communicates with the client. I wrapped this object in the c++/cli bridge code for the c# code to use it.

The bridge should also expose several functions with __declspec(dllexport) and pass those calls to the c# dll, so it needs to have a pointer to a c# interface to which it would pass them. I wanted to use a c# object with the gcroot<> wrapper, but the problem is that I get circular dependencies between these two dlls. C# dll needs to reference the bridge dll to be able to use the wrapper class and the bridge dll needs to reference the c# dll to use the interface class.

I know I can use COM instead of wrapping the c# object with gcroot, but I'd rather not. Is there any way around this?

回答1:

Just define the interface in C++/CLI instead of C#. This eliminates the dependency on the C# project entirely.

I recommend thinking of the C++/CLI project as nothing but a wrapper - don't define any new interfaces in there. Just take what is in the current C++ code, and wrap it in "ref classes" so you can construct and call them from C#.