简体   繁体   中英

Modify Java object field from JNI

i want to declare an int a = 5 in java (android) and modify it using ndk with c/c++ , and change the value of int a in jni , basically its accessing that segment of ram which variable is declared , but i dont know how to do that ?

public class dataclass {                                                                
int a = 5;                                                                          
int b = 5;                                                                          
                                                                                    
static {                                                                            
    System.loadLibrary("native-lib");                                               
}                                                                                   
public native void changeValue(dataclass mclass);                                 

}

Assuming you declared your changeValue as a static function in Java, your native code will receive three parameters: a JNIEnv * env , a jclass cls , and jobject obj . The latter is the instance of dataclass you want to manipulate.

The approach is then standard:

  1. Get a reference to the dataclass class using env->FindClass("dataclass") or env->GetObjectClass(obj)
  2. Use that reference to get a handle to the field you want to modify using env->GetFieldID(dataClass, "a", "I") . The I here is the primitive type associated with int .
  3. Finally, make the change by calling env->SetIntField(obj, fieldId, new_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