-
-
Notifications
You must be signed in to change notification settings - Fork 471
How to efficiently convert to a std::string? #1161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
@ronag, there is no need to do the copy twice. We can just copy the bytes directly to // Measure the string length
size_t str_length;
NODE_API_CALL(
env, napi_get_value_string_utf8(env, args[0], nullptr, 0, &str_length));
// Create std::string with the required size.
std::string utf8_str(str_length, '\0');
// Copy the napi_value string content to std::string
size_t copied;
NODE_API_CALL(
env,
napi_get_value_string_utf8(
env, args[0], &utf8_str[0], utf8_str.length() + 1, &copied)); Since |
Thanks! |
What is |
Also is it possible for |
This is a macro that checks that the function returns |
No, in that case it is not possible. Our unit tests check that must not happen. When we copy data to the buffer the result parameter is optional. If we skip testing error codes and number of copied bytes the code can be reduced to: size_t str_length;
napi_get_value_string_utf8(env, str_value, nullptr, 0, &str_length);
std::string utf8_str(str_length, '\0');
napi_get_value_string_utf8(env, str_value, &utf8_str[0], utf8_str.length() + 1, nullptr); |
Give how the API looks today is there an efficient way to convert a napi_value into a std::string without doing an extra copy? Currently in order to convert a nap string into a std::string we need to perform 2 copies. Would be nice to be able to at least reduce it to 1 copy. Would be even nicer if one could move/reference ownership i.e. 0 copy.
Refs: Level/classic-level#21
The text was updated successfully, but these errors were encountered: