如何在 .NET 中使用托管 DLL 中的非托管类?

发布于 2024-07-15 07:51:55 字数 406 浏览 6 评论 0原文

我有一个非托管类,我试图从托管 DLL 文件中导出它。 我正在尝试在另一个托管 DLL 文件中使用非托管类。 但是,当我尝试执行此操作时,我收到链接错误。

我已经多次使用非托管 DLL 文件执行此操作,因此我知道它是如何工作的。 我知道如何在托管类中使用“公共引用”等。

我需要在某个地方设置一些标志吗? 或者我必须做一些 DllImport 魔法吗?

这是在 .NET 2.0 和 Visual Studio 2005 上。

I have an unmanaged class that I'm trying to dllexport from a managed DLL file. I'm trying to use the unmanaged class in another managed DLL file. However, when I try to do this I get link errors.

I've done this lots of times with unmanaged DLL files, so I know how that works. I know how to use "public ref", etc. in managed classes.

Is there some flag somewhere I need to set? Or do I have to do some DllImport magic?

This is on .NET 2.0 and Visual Studio 2005.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寻找一个思念的角度 2024-07-22 07:51:55

如果您想从托管代码中使用非托管类,您可以:

  1. 使用一些令人讨厌的 P/Invoke 加载类成员函数(构造函数、析构函数等)并创建一个更糟糕的托管包装类来调用“真正的”成员函数。 当涉及虚拟方法时,情况会变得更糟。
  2. 第二种选择(在我看来更好)是编写 C++/CLI包装类(您提到您对此很熟悉),它是非托管类的简单代理。 对于非托管类中的每个成员函数,代理类中都会有一个类似的成员函数。 然后,这是一个从托管项目添加对该 DLL 的引用的简单情况,您将能够像使用任何其他 .NET 类一样使用您的类。 请考虑到,如果您的类公开其他非托管内容(无法编组的内容),您将遇到更多工作。

如果您需要有关第二个选项的更多信息,我可以查找一些旧链接来更多地解释此技术。

If you want to use an unmanaged class from managed code, you can:

  1. Use some nasty P/Invoke to load the class member functions (constructor, destructor, etc.) and make a nastier managed wrapper class to call the "real" member functions. This gets even worse when there are virtual methods involved.
  2. The second option (which in my opinion is better) is to write a C++/CLI wrapper class (you mentioned that you're familiar with this) that is a simple proxy to the unmanaged class. For every member function you have in the unmanaged class you'll have a similar one in your proxy class. Then it's a simple case of adding a reference to that DLL from your managed project, and you'll be able to use your class as any other .NET class. Take into consideration that you'll run into more work if your class exposes other unmanaged stuff (those that can't be marshalled).

If you need more information on the second option, I could look up some old links that explained this technique more.

梦在深巷 2024-07-22 07:51:55

您需要对非托管库或 COM 组件使用互操作程序集。 这是一个链接,其中包含有关此内容的详细信息。

You need to use an interop assembly for unmanaged libraries or COM components. Here is a link with good information regarding this.

穿越时光隧道 2024-07-22 07:51:55

如果它是 COM DLL 文件,那么您可以使用 COM .NET 互操作性。 Stack Overflow 问题是否有访问 C++ 本机 COM 函数以与 C# 进行互操作的最佳实践? 是另一个问题回答这个问题的问题。

If it is a COM DLL file then you can use COM .NET interoperability. Stack Overflow question Is there a best practice for accessing C++ native COM functions to interop from C#? is another question which answers this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文