使用 C++ C# 应用程序中的类 DLL
我有一个非托管 C++ DLL,它仅导出一个类(不是 COM...它只是一个简单的 C++ 类)作为其接口。 我想在 C# 中使用这个类,但被告知它不能仅仅导入到 C# 中。
在我的 C# 应用程序中使用此类的正确方法是什么?
I have an unmanaged C++ DLL which merely exports a single class (not COM...it's just a simple C++ class) as its interface. I want to use this class in C# but am told that it cannot merely be imported into C#.
What is the right way to use this class in my C# application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
DllImport 是您最好的选择。 有一些数据类型处理,特别是当您传递结构时,但您几乎可以用它做任何事情。
DllImport is your best bet. There is a bit of data type massaging, especially if you are passing structs, but you can do almost anything with it.
您需要一个代理(GoF 模式)中介来桥接托管/非托管边界。
两个选项:
前者会更直接,后者有两步纯C++ -> 通讯-> 。网。
You need an proxy (GoF pattern) intermediary to bridge the managed/unmanaged boundary.
Two options:
The former will be more direct, and latter has two steps pure C++ -> COM -> .NET.
有时,提供您自己的 C 接口会更容易。 SWIG 的设置并不简单。 我使用过托管 C++ 和 C++/CLI,它们都很好。 最简单的就是做一个 C 包装器(并且可以被任何其他语言使用,因为大多数语言都有调用 C 函数的方法)。
Sometimes, it is easier to provide your own C interface. SWIG is non-trivial to setup. I have use managed C++ and C++/CLI and they are fine. The easiest was just doing a C wrapper (and can be used by about any other language since most have a way to call a C function).
假设类 Foo 的简单方法:
你使你的 C# 代码依赖于 FooWrapper 项目/dll 并确保非托管 dll 与其一起正确部署,如何完成取决于非托管 dll,但在同一目录中通常就足够了。
如果函数不依赖于类的实例,则 P/Invoke 更简单
Simple way assuming class Foo:
Then you make your c# code depend on the FooWrapper project/dll and ensure that the unmanaged dll is properly deployed with it, how that is done depends on the unmanaged dll but in the same directory is normally sufficient.
If the functions do not rely on instances of the class then even simpler is P/Invoke
对于单个类库来说,这个答案可能有点过分了,但 SWIG 是“包装”C/C++ 类以供其他语言使用的良好解决方案。 它与 C# 配合良好。
参见 http://www.swig.org/。
This answer might be overkill for a single class library, but SWIG is a good solution for "wrapping" C/C++ classes for use from other languages. It works well with C#.
See http://www.swig.org/.