这是JNI代码。
Java代码:
public class Sample1 {
public native String stringMethod(String text);
public static void main(String[] args)
{
System.loadLibrary("Sample1");
Sample1 sample = new Sample1();
String text = sample.stringMethod("world");
System.out.println("stringMethod: " + text);
}
}
stringMethod函数的Cpp方法:
JNIEXPORT jstring JNICALL Java_Sample1_stringMethod
(JNIEnv *env, jobject obj, jstring string) {
const char *name = env->GetStringUTFChars(string, NULL);//Java String to C Style string
char msg[60] = "Hello ";
jstring result;
strcat(msg, name);
env->ReleaseStringUTFChars(string, name);
puts(msg);
result = env->NewStringUTF(msg); // C style string to Java String
return result;
}
运行我的java代码时。我得到了下面的结果。
stringMethod: world
但是我用“Hello”添加了字符串“world”。我也在这里返回附加的字符串。但为什么我只得到“世界”而不是“Hello World”。真的我对这段代码感到困惑。我该怎么做才能得到附加字符串的结果?
答案 0 :(得分:13)
这应该是这样做的方式....
JNIEXPORT jstring JNICALL Java_Sample1_stringMethod
(JNIEnv *env, jobject obj, jstring string) {
const char *name = (*env).GetStringUTFChars(env,string, NULL);
char msg[60] = "Hello ";
jstring result;
strcat(msg, name);
(*env).ReleaseStringUTFChars(env,string, name);
puts(msg);
result = (*env).NewStringUTF(env,msg);
return result;
}
答案 1 :(得分:0)
there are several ways but the best i got by converting const char * to c++ string
and then to jbyteArray, and its easy to conversion of byteArray to UTF-8 on java
side.
C++ side:
const char* string = propertyValue;
std::string str = string;
jbyteArray array = env->NewByteArray(str.length());
env->SetByteArrayRegion(array,0,str.length(),(jbyte*)str.c_str());
return array;
java/kotlin side:
String((array), Charset.defaultCharset()))