How to expose STL list over DLL boundary?

后端 未结 3 706
情话喂你
情话喂你 2021-02-02 02:42

I have a DLL which needs to access data stored in STL containers in the host application. Because C++ has no standard ABI, and I want to support different compilers, the interf

3条回答
  •  后悔当初
    2021-02-02 03:43

    You can pass stl objects between DLLs and support different compilers if you are careful where you instantiate each stl type. You need some intelligent "DLLEXPORT" macros -- I use the following set to successfully support VC and gcc.

    #ifdef WIN32
    #ifdef MYDLLLIB_EXPORTS      // DLL export macros
    #define MYDLLLIB_API __declspec(dllexport)
    #define MYDLLLIB_TEMPLATE
    #else
    #define MYDLLLIB_API __declspec(dllimport)
    #define MYDLLLIB_TEMPLATE extern
    #endif
    #else                       // Not windows --- probably *nix/bsd
    #define MYDLLLIB_API
    #ifdef MYDLLLIB_EXPORTS
    #define MYDLLLIB_TEMPLATE
    #else
    #define MYDLLLIB_TEMPLATE extern
    #endif
    #endif // WIN32
    

    When compiling your DLL, define MYDLLLIB_EXPORTS. In the DLL you can then instantiate each stl type you wish to use, for example, lists or vectors of strings

    MYDLLLIB_TEMPLATE template class MYDLLLIB_API std::vector;
    MYDLLLIB_TEMPLATE template class MYDLLLIB_API std::list;
    

    Consumers of your DLL (who don't have MYDLLLIB_EXPORTS defined) will then see

    extern template class __declspec(dllimport) std::vector;
    

    and use the binary code exported from your DLL instead of instantiating their own.

提交回复
热议问题