如何使用 C++ .net 项目中的类库
我的.net项目需要使用C++编写的第三方类库。我已经尝试从项目的上下文菜单“添加引用...”直接添加对此 DLL 的引用,但它不起作用,因为我假设该 DLL 没有实现 COM 对象模型。
我现在有什么选择?有些人建议围绕这个 DLL 创建一个 .net 包装器,但我过去从未这样做过,所以我正在寻找一个可能包含一些示例的简单介绍。我过去做过的最接近的事情是使用 pInvoke (例如,来自 win32.dll )从外部库调用方法,但在这种情况下,我可能还需要将本机 C++ 类型包装到它们在 .net 中的等效表示形式,并且可能还存在是一些要考虑的实例变量,所以我不知道 pInvoke 是否足够。
如果有人能指出我正确的方向,我将非常感激,如果需要更多信息,请告诉我。
非常感谢。
My .net project needs to use a third party class library written in C++. I have already tried directly adding a reference to this DLL from the project's context menu 'Add a refence...'' but it did not work as I assume this DLL does not implement the COM object model.
What options do I have now? Some suggest to create a .net wrapper around this DLL but I have never done it in the past so I'm looking for an easy introduction with possibly some examples. The closest thing I have done in the past was calling methods from an external library using pInvoke (from win32.dll for instance) but in this case I might also need to wrap native C++ types to their equivalent representation in .net and there might also be some instance variables to be accounted for so I don't know if the pInvoke will be sufficient.
I'd really appreciate if anyone could point me in the right direction and please let me know if more information is required.
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您没有该库的源代码,或者有其他原因导致您无法将库转换为 C++/CLI 程序集。
您可能对 SWIG 感兴趣( http://www.swig.org/ )包装生成器。您可以为 SWIG 提供 C++ 库的公共接口,它会为其支持的任何后端语言(C# 恰好是其中之一)编织一个包装器。
Assuming you don't have the source to the library or there is another reason why you can't transform the library into a C++/CLI assembly.
You might be interested in SWIG ( http://www.swig.org/ ) a wrapper generator. You can give SWIG the public interface to a C++ library and it knits a wrapper for any of its supported backend languages, which C# happens to be one of.
我知道有两个选项
There are 2 options that I know of
正如您所说,有两种方法可以做到这一点:
1)通过使用 P/Invoke 导入 C++ 函数。
2) 通过将非托管代码包装为托管代码,并使用“添加引用”将该库添加到您的 .net 应用程序中。 这里是一个简单的示例。
此链接将为您提供详细信息.net 互操作性。
其中 P/Invoke 是最简单的方法。对于 .net 中的 C++ 等效类型,您可以进行封送处理,这也很简单,您会发现很多相同的教程。
As you said there are 2 ways to do that:
1) By importing C++ functions using P/Invoke.
2) By wrapping unmanaged code to mananged and add that library in your .net application using 'Add Reference'. Here is the simple example for this.
This link will give you detailed information of .net interoperability.
Out of these P/Invoke is easiest way to do. For c++ equivalent types in .net, you can do marshaling which is also easy and you will find lot many tutorial for the same.