c++dllabi

Use of std::string_view in extern "C" DLL


I am designing a C++ DLL with extern "C" bindings for use in Python and C#. Some of the structures passed around currently contain C strings that I'm considering to change to std::string_view for following benefits:

  1. They are clearly non-owning (user of DLL does not call free)
  2. They are of known size, so user does not have to check it with strlen
  3. Because of that, they don't have to be null terminated, making substrings cheaper to create for DLL

Is std::string_view (and std::span<T> which is pretty much the same thing) guaranteed to be exactly { T*; size_t; }, or am I safer to create my own struct for it to maintain ABI across languages? cppreference lists "data members" which suggests the layout is guaranteed by the standard.


Solution

  • Is std::string_view (and std::span<T> which is pretty much the same thing) guaranteed to be exactly { T*; size_t; }

    No, you have no such guarantees. gcc for example declares the std::basic_string_view members in this order:

    size_t        _M_len;
    const _CharT* _M_str;
    

    or am I safer to create my own struct for it to maintain ABI across languages?

    Yes, that would be the safest.