Is there a better way to load a dll in C++?

前端 未结 7 1340
北海茫月
北海茫月 2020-12-13 16:46

Right now I do something like this and it seems messy if I end having a lot of functions I want to reference in my DLL. Is there a better and cleaner way of accessing the fu

7条回答
  •  北海茫月
    2020-12-13 17:04

    You can link to the DLL's symbols directly instead of using GetProcAddress(), which gets the address of a function at runtime.

    Example header file snippet:

    #if defined(MY_LIB_STATIC)
    #define MY_LIB_EXPORT
    #elif defined(MY_LIB_EXPORTS)
    #define MY_LIB_EXPORT __declspec(dllexport)
    #else
    #define MY_LIB_EXPORT __declspec(dllimport)
    #endif
    
    #ifdef __cplusplus
    extern "C"
    {
    #endif
    
    int MY_LIB_EXPORT Factorial(int n);
    
    #ifdef __cplusplus
    }
    #endif
    

    Then in BHannan_Test_Class.cpp, you would #define MY_LIB_EXPORTS before including the header.

    In dll_test.cpp you would include the header and just use Factorial() as you would use a normal function. When linking, you want to link to the import library that building your DLL produced. This makes the symbols from the DLL available to the code that links to it.

提交回复
热议问题