Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::string_view with api, what expects null terminated string

Tags:

c++

c++17

I have a method that takes std::string_view and uses function, which takes null terminated string as parameter. For example:

void stringFunc(std::experimental::string_view str) {
    some_c_library_func(/* Expects null terminated string */);
}

The question is, what is the proper way to handle this situation? Is str.to_string().c_str() the only option? And I really want to use std::string_view in this method, because I pass different types of strings in it.

like image 477
Schtolc Avatar asked Dec 22 '16 15:12

Schtolc


People also ask

Is String_view null-terminated?

Unlike C-style strings and std::string , std::string_view doesn't use null terminators to mark the end of the string. Rather, it knows where the string ends because it keeps track of its length.

Is std :: string always null-terminated?

Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .

What happens if you dont null terminate a string?

If you use a non-null-terminated char sequence as a string, C functions will just keep going. It's the '\0' that tells them to stop. So, whatever happens to be in memory after the sequence will be taken as part of the string.

What does it mean for a string to be null-terminated?

In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character (a character with a value of zero, called NUL in this article).


1 Answers

I solved this problem by creating an alternate string_view class called zstring_view. It's privately inherited from string_view and contains much of its interface.

The principal difference is that zstring_view cannot be created from a string_view. Also, any string_view APIs that would remove elements from the end are not part of the interface or they return a string_view instead of a zstring_view.

They can be created from any NUL-terminated string source: std::string and so forth. I even created special user-defined literal suffixes for them: _zsv.

The idea being that, so long as you don't put a non-NUL-terminated string into zstring_view manually, all zstring_views should be NUL-terminated. Like std::string, the NUL character is not part of the size of the string, but it is there.

I find it very useful for dealing with C interfacing.

like image 105
Nicol Bolas Avatar answered Oct 09 '22 06:10

Nicol Bolas