Id like to make a simple function, that return value of two Strings, basically:
java
public native String getAppendedString(String name);
c
jstring Java_com_example_hellojni_HelloJni_getAppendedString(JNIEnv* env, jobject thiz, jstring s) {
jstring sx = (*env)->GetStringUTFChars(env, s, NULL);
return ((*env)->NewStringUTF(env, "asd ")+sx);
}
It returns:
jni/hello-jni.c:32: warning: initialization discards qualifiers from pointer target type
jni/hello-jni.c:34: error: invalid operands to binary + (have 'char *' and 'char *')
The retval will be: "asd qwer", how can I do this?
jstring s1 = (*env)->NewStringUTF(env, "456");
jstring s2 = (*env)->NewStringUTF(env, "123");
jstring sall=strcat(s1, s2);
return sall;
Only returns "456"
There are a few issues here:
GetStringUTFCharsreturns ajbyte *(a null-terminated C string), not ajstring. You need this C string to do string manipulation in C.You need to call
ReleaseStringUTFCharswhen you’re done with it.You need to allocate enough memory to hold the concatenated string, using
malloc.As ethan mentioned, you need to concatenate your two C strings with
strcat. (You cannot do this with the+operator. When applied to a pointer,+returns the pointer from the offset of the original pointer.)Remember to free the memory you allocated after you’re done with it (ie, after it’s been interned as a Java string.)
You should do something along the lines of: