从DLL导出C ++类 [英] Exporting a C++ class from a DLL
问题描述
我的大多数C / C ++开发涉及单片模块文件,绝对没有任何类,所以通常当我需要使用可访问函数创建一个 DLL 时,我只是使用标准 __ declspec(dllexport)
指令。然后通过 LoadLibrary()
动态访问它们,或在编译时使用头文件和lib文件。
当你想导出整个类(以及它的所有公共方法和属性)时,如何做?
是否可以在运行时动态加载该类,如果是,如何?
如何使用头文件和lib进行编译时链接? / p>
后期绑定呢?在加载
它与LoadLibrary()和
GetProcAddress()?我使用能够
在运行时加载库,它
将是伟大的,如果你可以做那个
这里。
因此,有两种方法来加载DLL。第一个是引用DLL中的一个或多个符号(例如你的类名),提供一个适当的导入.LIB,让链接器把所有的东西都输出。
第二个是通过LoadLibrary显式加载DLL。
这两种方法对C级函数导出都很好。你可以让链接器处理它或调用GetProcAddress,如你所说。
但是,当涉及到导出的类,通常只有第一种方法被使用,即,隐式链接到DLL。在这种情况下,DLL在应用程序启动时加载,如果找不到DLL,应用程序将无法加载。
如果要链接到类在DLL中定义,并且您希望该DLL被动态加载,有时在程序启动后,您有两个选项:
所有的事情都可以考虑...可能最好使用隐式链接,在这种情况下,你肯定想使用上面所示的预处理器技术。事实上,如果你在Visual Studio中创建一个新的DLL并选择导出符号选项,这些宏将为你创建。
祝你好运...
Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a DLL with accessible functions I just export them using the standard __declspec(dllexport)
directive. Then access them either dynamically via LoadLibrary()
or at compile time with a header and lib file.
How do you do this when you want to export an entire class (and all it's public methods and properties)?
Is it possible to dynamically load that class at runtime and if so, how?
How would you do it with a header and lib for compile time linking?
What about late-binding? As in loading it with LoadLibrary() and GetProcAddress() ? I'm used being able to load the library at run time and it would be great if you could do that here.
So there are two ways to load the DLL. The first is to reference one or more symbols from the DLL (your classname, for example), supply an appropriate import .LIB and let the linker figure everything out.
The second is to explicitly load the DLL via LoadLibrary.
Either approach works fine for C-level function exports. You can either let the linker handle it or call GetProcAddress as you noted.
But when it comes to exported classes, typically only the first approach is used, i.e., implicitly link to the DLL. In this case the DLL is loaded at application start time, and the application fails to load if the DLL can't be found.
If you want to link to a class defined in a DLL, and you want that DLL to be loaded dynamically, sometime after program initiation, you have two options:
Create objects of the class using a special factory function, which internally will have to use (a tiny bit of) assembler to "hook up" newly created objects to their appropriate offsets. This has to be done at run-time AFTER the DLL has been loaded, obviously. A good explanation of this approach can be found here.
Use a delay-load DLL.
All things considered... probably better to just go with implicit linking, in which case you definitely want to use the preprocessor technique shown above. In fact, if you create a new DLL in Visual Studio and choose the "export symbols" option these macros will be created for you.
Good luck...
这篇关于从DLL导出C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!