Dynamic Loading of C Classes from a DLL
Exporting an entire C class from a DLL enables the dynamic loading of its public methods and properties.
Compile-Time Linking with Header and Lib
For compile-time linking, use the standard __declspec(dllexport) directive within the class declaration. This exposes the class symbols to the compiler. Create a header (.h) file containing the class declaration and a library (.lib) file containing the symbol definitions. When linking the executable, include the header and link with the library.
Dynamic Loading at Runtime
Dynamically loading a class is possible with LoadLibrary() and GetProcAddress(). However, this approach is typically not used with classes due to issues with late-binding.
Factory Function Approach
To dynamically link to a class after loading the DLL, use a factory function that utilizes assembler to connect newly created objects to their appropriate offsets. This method ensures proper class functionality. Refer to the provided link for further details.
Delay-Load DLL
Delay-load DLLs allow the DLL to be loaded at a later time. This option involves defining a thunk function within the EXE that dynamically loads the DLL when needed. However, it requires additional configuration and may introduce performance penalties.
Implicit Linking with Preprocessor Macros
Implicit linking involves referencing symbols from the DLL and relying on the linker to resolve them. This approach is suitable if the DLL is loaded at application start-up. Using preprocessor macros (e.g., _declspec(dllimport)) in the header file exposes the exported class symbols to the compiler.
Recommendation
Implicit linking with preprocessor macros is generally recommended for dynamic loading of C classes. It provides efficient symbol resolution and compatibility with common development tools like Visual Studio.
The above is the detailed content of How to Dynamically Load C Classes from a DLL: Implicit Linking vs. Dynamic Loading?. For more information, please follow other related articles on the PHP Chinese website!