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);
}
Advertisement
Answer
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:
- Get a reference to the
dataclassclass usingenv->FindClass("dataclass")orenv->GetObjectClass(obj) - Use that reference to get a handle to the field you want to modify using
env->GetFieldID(dataClass, "a", "I"). TheIhere is the primitive type associated withint. - Finally, make the change by calling
env->SetIntField(obj, fieldId, new_value)