How do I safely pass objects, especially STL objects, to and from a DLL?

后端 未结 4 1125
Happy的楠姐
Happy的楠姐 2020-11-22 14:40

How do I pass class objects, especially STL objects, to and from a C++ DLL?

My application has to interact with third-party plugins in the form of DLL files, and I c

4条回答
  •  星月不相逢
    2020-11-22 15:38

    @computerfreaker has written a great explanation of why the lack of ABI prevents passing C++ objects across DLL boundaries in the general case, even when the type definitions are under user control and the exact same token sequence is used in both programs. (There are two cases which do work: standard-layout classes, and pure interfaces)

    For object types defined in the C++ Standard (including those adapted from the Standard Template Library), the situation is far, far worse. The tokens defining these types are NOT the same across multiple compilers, as the C++ Standard does not provide a complete type definition, only minimum requirements. In addition, name lookup of the identifiers that appear in these type definitions don't resolve the same. Even on systems where there is a C++ ABI, attempting to share such types across module boundaries results in massive undefined behavior due to One Definition Rule violations.

    This is something that Linux programmers weren't accustomed to dealing with, because g++'s libstdc++ was a de-facto standard and virtually all programs used it, thus satisfying the ODR. clang's libc++ broke that assumption, and then C++11 came along with mandatory changes to nearly all Standard library types.

    Just don't share Standard library types between modules. It's undefined behavior.

提交回复
热议问题