Skip to content

Commit

Permalink
Add a function to construct std::string from native_jstring
Browse files Browse the repository at this point in the history
  • Loading branch information
ttnghia committed Feb 11, 2022
1 parent 1b4cd51 commit 00d7d8b
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions java/src/main/native/include/jni_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

#include <jni.h>
Expand Down Expand Up @@ -524,7 +525,7 @@ class native_jstring {
void init_cstr() const {
if (orig != NULL && cstr == NULL) {
cstr_length = env->GetStringUTFLength(orig);
cstr = env->GetStringUTFChars(orig, 0);
cstr = env->GetStringUTFChars(orig, 0); // not guarantee to have null terminated.
check_java_exception(env);
}
}
Expand Down Expand Up @@ -555,6 +556,7 @@ class native_jstring {

bool is_null() const noexcept { return orig == NULL; }

// Note that the char* return by this function is not guaranteed to be null-terminated.
const char *get() const {
init_cstr();
return cstr;
Expand All @@ -565,6 +567,12 @@ class native_jstring {
return cstr_length;
}

// Note that the char* return by `get()` is not guaranteed to be null-terminated.
// Thus, constructing an std::string should be performed with a string size supplied.
std::string get_cpp_str() const { return std::string(get(), size_bytes()); }

jstring get_jstring() const { return orig; }

bool is_empty() const {
if (cstr != NULL) {
return cstr_length <= 0;
Expand All @@ -576,8 +584,6 @@ class native_jstring {
return true;
}

const jstring get_jstring() const { return orig; }

~native_jstring() {
if (orig != NULL && cstr != NULL) {
env->ReleaseStringUTFChars(orig, cstr);
Expand Down

0 comments on commit 00d7d8b

Please sign in to comment.