JNI 傳字符串參數,只輸出了第一個字符

如下邊的代碼,

運行結果:

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);
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章