非托管 C++ 的 C# 包装器
我发现这里有人提出了关于用 C# 包装非托管 C++ 的类似问题,但它们似乎都与特定的实现问题有关。我想知道使用 C# 和非托管 C++ 时的一般方法是什么。
例如,我有很多用非托管 C++ 编写的类,我希望能够通过 .NET 使用它们(最好是在 Excel 中使用 VBA)。到目前为止,我一直在使用托管 C++/CLI 来执行此操作,但是我注意到我宁愿避免使用该语言的一些奇怪之处。进一步阅读,似乎我可以将非托管 C++ 包装在 C# 中,然后直接访问 .NET(同时完全避免托管 C++/CLI)。这可能吗?如果可能的话,最好的方法是什么?谢谢你的帮助。
I see that there have been similar questions asked here regarding wrapping unmanaged C++ with C# but they all seem to be about specific implementation issues. I'd like to know what the general approach is when using C# and unmanaged C++.
For example, I have quite a few classes written in unmanaged C++ that I want to be able to use through .NET (ideally with VBA in Excel). I've been using managed C++/CLI to do this so far, however have noticed some oddities with the language that I'd rather avoid. Reading further it seems as though I could wrap my unmanaged C++ in C# and then have direct access to .NET (while completely avoiding managed C++/CLI). Is this possible and if so what's the best way to go about it? Thank you for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有三种选择:
如果您的目标确实是 Excel/VBA,那么由于您无论如何都会创建 COM 对象,所以我会选择选项 2 并直接使用 ATL 来创建 COM 类。虽然这完全绕过了 .NET,但使用 .NET 在 C++ 代码和 Excel 之间进行交互对我来说一直是个麻烦。
You have three choices:
If your goal is really Excel/VBA, since you're going to make COM objects anyway, I'd go with option 2 and make COM classes directly using ATL. This bypasses .NET completely though, but using .NET to interface between C++ code and Excel has always been a hassle for me.
如果您想完全避免使用 C++/CLI 并使用纯 C# 来访问本机代码,那么必须通过直接 P/Invoke 逐个方法进行。如果您有大量非托管代码,这几乎肯定不理想。
就我个人而言,我认为“最佳”解决方案是继续使用 C++/CLI 围绕本机代码编写托管包装器,公开尽可能简单的公共接口以降低复杂性。
If you're wanting to avoid C++/CLI completely and use pure C# to access your native code, then it would have to be through direct P/Invoke, method by method. This is almost certainly not ideal if you have a large amount of unmanaged code.
Personally, I would think the "best" solution would be to continue using C++/CLI to write managed wrappers around your native code that expose the simplest possible public interfaces to reduce the complexity.