In my C++ application, I use an external library that exposes a C API. Some of the C functions take arrays of strings as input and use char**
for that:
void c_api_function(char** symbols, int count);
(Note: I think a pointer to const would be more appropriate, but it seems as if const correctness was not important for the library authors.)
The strings must use a specific encoding.
Currently, in order to call the API, I first convert the strings to the correct encoding and store the result in a vector<string>
. Then I create a vector<char*>
that can be passed to the C API:
std::string encode(std::string const& symbol);
void call_api(std::vector<std::string> const& symbols)
{
std::vector<std::string> encoded_symbols;
for (auto const& s : symbols)
{
encoded_symbols.push_back(encode(s));
}
std::vector<char*> encoded_symbol_ptrs;
for (auto const& s : encoded_symbols)
{
encoded_symbols_ptrs.push_back(s.data());
}
c_api_function(encoded_symbols_ptrs.data(), (int)encoded_symbols_ptrs.size());
}
I dont like this approach, because I need two vectors. The first vector ensures that the strings are kept alive, the second vector can be passed to the API. Is there a way that only uses a single container, but still uses automatic memory management? If necessary, I can freely change the signature of the encode
function, for example, using std::unique_ptr
as return value.