可以调用 C++ 来自 C# 的代码?
是否可以从 .NET 语言(例如 C#)中调用 C++ 代码(可能编译为代码库文件 (.dll))?
具体来说,C++ 代码,例如 RakNet 网络库。
Is it possible to call C++ code, possibly compiled as a code library file (.dll), from within a .NET language such as C#?
Specifically, C++ code such as the RakNet networking library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
调用 C++ 的一种简单方法是在 C++/CLI 中创建包装器程序集。 在 C++/CLI 中,您可以像编写本机代码一样调用非托管代码,但也可以从 C# 调用 C++/CLI 代码,就像用 C# 编写一样。 该语言基本上是通过与现有库的互操作来设计的,作为其“杀手级应用程序”。
例如 - 使用 /clr 开关编译它
然后在 C# 中,添加对 ManagedType 程序集的引用,并像这样使用它:
查看 此博文 获取更详细的示例。
One easy way to call into C++ is to create a wrapper assembly in C++/CLI. In C++/CLI you can call into unmanaged code as if you were writing native code, but you can call into C++/CLI code from C# as if it were written in C#. The language was basically designed with interop into existing libraries as its "killer app".
For example - compile this with the /clr switch
Then in C#, add a reference to your ManagedType assembly, and use it like so:
Check out this blog post for a more explained example.
P/Invoke 是一项很好的技术,除了加载目标 DLL 文件时存在问题外,它运行得相当好。 我们发现最好的方法是创建本机函数的静态库并将其链接到依赖于它的托管 C++(或 C++/CLI)项目。
P/Invoke is a nice technology, and it works fairly well, except for issues in loading the target DLL file. We've found that the best way to do things is to create a static library of native functions and link that into a Managed C++ (or C++/CLI) project that depends upon it.
我不熟悉您提到的库,但一般来说有几种方法可以做到这一点:
I'm not familiar with the library you mentioned, but in general there are a couple ways to do so:
当然是。 这篇文章是一个很好的示例,您可以这样做开始吧。
我们使用 P/Invoke 在 Windows Mobile 设备上通过 C# 执行此操作。
Sure is. This article is a good example of something you can do to get started on this.
We do this from C# on our Windows Mobile devices using P/Invoke.
用于执行此操作的技术称为 P/Invoke; 您可以搜索有关该主题的文章。 请注意,它是用于从 C# 调用 C,而不是 C++。 因此,您需要将 C++ 代码包装在 DLL 导出的 C 包装器中。
The technology used to do this is called P/Invoke; you can search for articles on the subject. Note that it is for calling C from C#, not C++ so much. So you'll need to wrap your C++ code in a C wrapper that your DLL exports.
您考虑过 Apache Thrift 吗?
http://thrift.apache.org/
这似乎是一个非常非常简洁的解决方案。
Have you considered Apache Thrift?
http://thrift.apache.org/
It seems like a very very neat solution.
是的,它称为 P/Invoke。
这是一个很好的资源网站,可将其与 Win32 API 一起使用:
http://www.pinvoke.net/
Yes, it is called P/Invoke.
Here's a great resource site for using it with the Win32 API:
http://www.pinvoke.net/