Skip to content

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 {                                                                            
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)