Skip to content

Commit

Permalink
refactor jstring2string
Browse files Browse the repository at this point in the history
  • Loading branch information
baibaichen committed Jul 5, 2024
1 parent 879dc2e commit aea4db0
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions cpp-ch/local-engine/local_engine_jni.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,13 @@ static std::string jstring2string(JNIEnv * env, jstring jStr)
if (!jStr)
return "";

jclass string_class = env->GetObjectClass(jStr);
jmethodID get_bytes = env->GetMethodID(string_class, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray string_jbytes
const jclass string_class = env->GetObjectClass(jStr);
const jmethodID get_bytes = env->GetMethodID(string_class, "getBytes", "(Ljava/lang/String;)[B");
const auto string_jbytes
= static_cast<jbyteArray>(local_engine::safeCallObjectMethod(env, jStr, get_bytes, env->NewStringUTF("UTF-8")));

size_t length = static_cast<size_t>(env->GetArrayLength(string_jbytes));
jbyte * p_bytes = env->GetByteArrayElements(string_jbytes, nullptr);

std::string ret = std::string(reinterpret_cast<char *>(p_bytes), length);
env->ReleaseByteArrayElements(string_jbytes, p_bytes, JNI_ABORT);
const auto string_jbytes_a = local_engine::getByteArrayElementsSafe(env, string_jbytes);
std::string ret{reinterpret_cast<char *>(string_jbytes_a.elems()), static_cast<size_t>(string_jbytes_a.length())};

env->DeleteLocalRef(string_jbytes);
env->DeleteLocalRef(string_class);
Expand Down

0 comments on commit aea4db0

Please sign in to comment.