我应该如何用 C++ 编写我的 lib用于.NET?
我有一个用 C++ 编写的库的原型。它是 CPU 密集型的,所以我用 C(因为工具)编写了一部分,用 C++ 编写了一部分,并使用了自定义内存分配器和各种东西。
我想在.NET 中使用这个库。我不太确定应该怎么做。看来我应该编写一个 C 接口并在 .NET 中编写一个包装器来使用托管 C++,我假设我有完全相同的代码文件,除了添加一个或两个文件并为它们编写一个托管类。
如果我选择托管路线,我应该了解哪些好处或限制?
I have a prototype for a lib written in C++. It is CPU intensive so I wrote one part in C (because of tools) the meat in C++ and used custom memory allocators and various things.
I would like to use this lib in .NET. I'm not exactly sure how I should do it. It seems like I should either write a C interface and write a wrapper in .NET to use managed C++ which I am assuming I have the exact same code files except I add a file or two and write a managed class for them.
What are the benefits or restrictions I should know about if I go the managed route?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++/CLI 就是您正在寻找的答案。 C++/CLI 的优点在于它允许您将本机 C++ 与 .NET 代码混合,您可以使用它来构建供 .NET 开发人员使用的库。以下 MSDN 文章很好地介绍了它的工作原理:
http://msdn。 microsoft.com/en-us/magazine/cc163852.aspx
希望这有帮助!
C++/CLI is the answer you're looking for. The beauty of C++/CLI is that it allows you to mix native C++ with .NET code, which you can use to build a library for consumption by .NET developers. The following MSDN article is a great introduction to how it works:
http://msdn.microsoft.com/en-us/magazine/cc163852.aspx
Hope this helps!
这取决于 C++ 库和 .NET 代码之间的“表面接触”(顺便说一句,无论您选择什么方式,您都需要将其公开为 DLL)
如果您确实拥有一个包含类、方法、属性的完全面向对象的库,即:对象模型,您可以使用 C++/CLI,因此集成将会非常透明。缺点是您必须了解它的一些微妙之处(而且我认为您对于如何嵌入 MSVC 运行时也有一些限制)。
如果您可以将 API 简化为一组有限的方法,那么您可以导出其中一些方法并使用 P/Invoke(DllImport 属性。请参阅此处的教程:平台调用教程)。在这种情况下,请确保公开的参数可由 .NET 层使用(不要使用复杂的 C/C++ 类型、指向指针的指针,...,不要使用 C++ 类,...),并尝试确保内存分配由.NET 端完成。
PS:顺便说一句,您应该考虑 32 位/64 位问题。你们的 DLL 在 64 位中可用吗?你们会分发这两个版本吗? .NET 两者都有能力。
It depends on the "surface contact" between your C++ library and your .NET code (BTW, you'll need to expose it as a DLL whatever way you choose)
If you really have a fully object oriented library with classes, methods, properties, i.e: an object model, you can go for the C++/CLI, so the integration will be quite transparent. The drawback is you'll have to understand some of its subtleties (and I think you also have some constraints about how you'll embed the MSVC runtime).
If you can reduce the API to a finite set of methods, than you can just export some of these methods and use P/Invoke (DllImport attribute. See this tutorial here: Platform Invoke Tutorial). In this case, make sure the exposed parameters will be consumable by the .NET layer (don't use complex C/C++ types, pointers to pointers to pointers, ..., don't use C++ classes, ...), and try to ensure memory allocation will be done by the .NET side.
PS: as a side note, you should think about the 32-bit / 64-bit issue. Will you DLL be available in 64-bit? Will you distribute both version? .NET is capable of both.