从 DLL 导出 C++ 类
我的大部分 C/C++ 开发都涉及单片模块文件,绝对没有任何类,所以通常当我需要使用可访问的函数制作 DLL 时,我只是使用标准的 __declspec 导出它们(dllexport)
指令.然后通过 LoadLibrary()
动态访问它们,或者在编译时使用头文件和 lib 文件访问它们.
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?
推荐答案
后期绑定呢?如在加载它与 LoadLibrary() 和GetProcAddress() ?我习惯了在运行时加载库和它如果你能那样做就好了在这里.
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.
所以有两种方法可以加载DLL.第一个是从 DLL 中引用一个或多个符号(例如您的类名),提供适当的导入 .LIB 并让链接器解决所有问题.
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.
第二种是通过LoadLibrary显式加载DLL.
The second is to explicitly load the DLL via LoadLibrary.
任何一种方法都适用于 C 级函数导出.您可以让链接器处理它,也可以按照您的说明调用 GetProcAddress.
Either approach works fine for C-level function exports. You can either let the linker handle it or call GetProcAddress as you noted.
但是当涉及到导出的类时,通常只使用第一种方法,即隐式链接到 DLL.在这种情况下,DLL 是在应用程序启动时加载的,如果找不到 DLL,应用程序将无法加载.
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.
如果要链接到 DLL 中定义的类,并且希望动态加载该 DLL,则在程序启动后的某个时间,您有两个选择:
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:
使用特殊的工厂函数创建类的对象,该函数在内部必须使用(一点点)汇编程序将新创建的对象连接"到其适当的偏移量.显然,这必须在 DLL 加载后的运行时完成.可以在此处找到对这种方法的很好解释.
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.
使用延迟加载 DLL.p>
考虑到所有事情......可能最好使用隐式链接,在这种情况下,您肯定希望使用上面显示的预处理器技术.事实上,如果您在 Visual Studio 中创建一个新的 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.
祝你好运...
相关文章