如下邊的代碼,
運行結果:
Result: H
Java代碼:
public class Test { public void print(String msg); static { System.loadLibrary("MyJni"); } public static void main(String[] args) { Test t = new Test(); System.out.print("Result: "); t.print("Hello, World!"); } }
C:
JNIEXPORT void TestJni_print(JNIEnv * env, jobject obj, jstring str) {
const char * str_buf = (*env)->GetStringChars(env, str, NULL);
printf("constent is %s", str_buf);
(*env)->ReleaseStringChars(env, str, str_buf);
}
正確的寫法:
JNIEXPORT void JNICALL Java_TestJni_print
(JNIEnv * env, jobject obj, jstring str) {
const char * str_buf = (*env)->GetStringUTFChars(env, str, NULL);
printf("constent is %s", str_buf);
(*env)->ReleaseStringUTFChars(env, str, str_buf);
}