从DLL导出C ++类 [英] Exporting a C++ class from a 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屋!