简体   繁体   中英

JNI pass by reference fails

I have the following code in Java:

class Foo {
   public native int bar(String name);

   public static void main(String[] args) {
     Foo fo = new Foo();
     String n = "Name1";
     fo.(n);
     System.out.println(n);
   }
}

And in CI have:

    JNIEXPORT jint JNICALL Java_com_ehsunbehravesh_j7_j7win_windows_Computer_getComputerName
(JNIEnv *env, jobject obj, jstring name) {
      name = (*env)->NewStringUTF(env, "Name2");  
      return 0;
    }

I assume the result on the screen should be Name2 But it is Name1

Strings are immutable. Why not just return it instead?

 public native String bar();

[..]

 JNIEXPORT jstring JNICALL Java_com_ehsunbehravesh_j7_j7win_windows_Computer_getComputerName
      (JNIEnv *env, jobject obj)
 {
     return (*env)->NewStringUTF(env, "Name2");  
 }

In the C code, name is a local variable. Changing it will not change the string object to which it formerly pointed. In addition, java String's are immutable, so you can't change the object. What you could do would be to return the reference to a new String, since you're not using the integer return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM