Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI Accessing Object's Instance Variables

I am trying write in a instance object variable on Java:

public class Test {
  public Test () {
    System.load("path_lib");
    this.jni_result = 0;
  }

  public PrintVar() {
    JniTest();
    System.out.println("jni_result: " + Long.toString(this.jni_result));
  }

  private native long JniTest();
  private long jni_result;
}

In C code I created the function to write in a variable

static void
SetErrorVariable(JNIEnv *env, jobject jobj, long error) {
  /* Get a reference to jctf object's class */
  jclass TestClass = env->GetObjectClass(jobj);

  /* Get the Field ID of the instance variables "jni_result" */
  jfieldID fidError = env->GetFieldID(TestClass, "jni_result", "J");

  /* Change the variable "jni_result" */
  jlong jerror = (jlong) error;
  env->SetLongField(TestClass, fidError, jerror);
}

JNIEXPORT jlong JNICALL
Java_Test_JniTest(JNIEnv *env, jobject jobj) {
  SetErrorVariable(env, jobj, -5)

  return (jlong) -5;
}

I can read the return of JniTest when I change the return in C code, but the variable I cant change, I read several tutorials of JNI but I didnt find other way to do that, where am I wronging?

like image 266
Alex Avatar asked Jan 11 '23 10:01

Alex


2 Answers

To get the fieldID, you need to pass the class, which is what you're doing here:

jfieldID fidError = env->GetFieldID(TestClass, "jni_result", "J");

To set the field of an instance of the class, you need to pass the instance of that class, otherwise how does it know what instance of the class to set the value on? TestClass is the class, obj is an instance of the class. You're passing TestClass. So change this:

env->SetLongField(TestClass, fidError, jerror);

To this:

env->SetLongField(obj, fidError, jerror);
like image 184
orfdorf Avatar answered Jan 19 '23 07:01

orfdorf


I think you made a typo when writing env->SetLongField(TestClass, fidError, jerror); instead of env->SetLongField(jobj, fidError, jerror);.

Could you please verify, if this is sufficient?

like image 40
pproksch Avatar answered Jan 19 '23 09:01

pproksch