Using DLLImport to import a class

倖福魔咒の 提交于 2019-12-07 15:31:08

问题


I have an class in dll: For example:

namespace foo {
   public class baa {
      /* ... */
  }
}

how can I imports the baa class from dll? it is possible?

[DllImport(DllName)]
public extern ?? foo() ??

Thanks in advance.


回答1:


That's not going to work. Unmanaged DLLs export a C interface, not a C++ one. And for managed DLLs (C# or C++/CLI) you simply don't need DllImport.

Only functions that are imported into a static class I'm afraid.




回答2:


DllImport is used only when you want to invoke unmanaged functions from an unmanaged library (like one written in C++).

When you have a managed .NET assembly you simply add it as reference to your project and use it.

So assuming you have a .NET class library containing the following class:

namespace foo {
   public class baa {
      /* ... */
  }
}

and then you have some other project that needs to use this assembly you go to the References node in the Solution Explorer and Add Reference to the given assembly. Then you bring the namespace into scope:

using foo;

and instantiate the class:

baa b = new baa();
... use the b instance here



回答3:


That's a standard C++ export mechanism that only works with C++. You can't import it from C# directly. There are workarounds, like exporting a managed type from a MC++ assembly, use a separate managed wrapper, using COM and a type library or something like that, but you can't use the same import/export mechanism C++ applications use.



来源:https://stackoverflow.com/questions/8043545/using-dllimport-to-import-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!