使用c ++ / cli网桥连接c ++和c#代码 [英] Connecting c++ and c# code with a c++/cli bridge

查看:144
本文介绍了使用c ++ / cli网桥连接c ++和c#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

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.

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

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?

推荐答案

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

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

我建议认为C ++ / CLI项目只是一个包装器 - 不要定义任何新的接口。只需取得当前C ++代码中的内容,并将其包装在ref classes中,以便可以从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 ++和c#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆