Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

dll

abi

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.

like image 247
Dominik Kaszewski Avatar asked Sep 01 '25 03:09

Dominik Kaszewski


1 Answers

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.

like image 185
Ted Lyngmo Avatar answered Sep 02 '25 16:09

Ted Lyngmo