How to convert jstring
(JNI) to std::string
(c++) with utf8
characters?
this is my code. it worked with non-utf8 characters, but i
explanation is here:
http://www.club.cc.cmu.edu/~cmccabe/blog_jni_flaws.html https://developer.android.com/training/articles/perf-jni (Region calls)
jsize
string_j2c(JNIEnv *env, jstring p, char *buffer) {
if (buffer != NULL) {
// Returns the length (the count of Unicode characters) of a
// Java string.
const jsize len = (*env).GetStringLength(p);
// Translates 'len' number of Unicode characters into modified
// UTF-8 encoding and place the result in the given buffer.
(*env).GetStringUTFRegion(p, 0, len, buffer);
// Returns JNI_TRUE when there is a pending exception;
// otherwise, returns JNI_FALSE.
const jboolean is_error = (*env).ExceptionCheck();
if (is_error == JNI_TRUE) {
return -1;
}
}
// Returns the length in bytes of the modified UTF-8
// representation of a string.
const jsize len = (*env).GetStringUTFLength(p);
return len;
}
const jsize len = string_j2c(env, p, NULL);
char buffer[len];
const jsize ret = string_j2c(env, p, buffer);
if (ret == -1) { // error
}
else {
__android_log_print(ANDROID_LOG_DEBUG, "Native", "%s", buffer);
}