使用c ++ / cli桥连接c ++和c#代码

时间:2022-09-01 09:51:24

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.

我有一个使用本机c ++ dll的本机c ++代码的客户端应用程序。我正在调查将此代码与c#dll连接的可能性,因为它们更容易编写。我决定编写一个c ++ / cli bridge dll,它可以加载LoadLibrary并将调用传递给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.

客户端和dll之间的通信使得客户端传递指向接口对象的指针,然后dll通过该接口对象与客户端通信。我将此对象包装在c ++ / cli桥接代码中,以便使用c#代码。

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.

桥接器还应该使用__declspec(dllexport)公开几个函数,并将这些调用传递给c#dll,因此它需要有一个指向c#接口的指针,它将传递给它们。我想在gcroot <>包装器中使用c#对象,但问题是我在这两个dll之间得到循环依赖。 C#dll需要引用bridge dll才能使用包装类,而bridge dll需要引用c#dll来使用接口类。

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?

我知道我可以使用COM而不是用gcroot包装c#对象,但我不想。有没有办法解决?

1 个解决方案

#1


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

只需在C ++ / CLI中定义接口而不是C#。这完全消除了对C#项目的依赖。

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#.

我建议将C ++ / CLI项目视为包装器 - 不要在其中定义任何新接口。只需获取当前C ++代码中的内容,并将其包装在“ref classes”中,以便您可以从C#构造和调用它们。

#1


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

只需在C ++ / CLI中定义接口而不是C#。这完全消除了对C#项目的依赖。

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#.

我建议将C ++ / CLI项目视为包装器 - 不要在其中定义任何新接口。只需获取当前C ++代码中的内容,并将其包装在“ref classes”中,以便您可以从C#构造和调用它们。