I am trying to access "int" field in the Java class from C++; Actually I also tried other types. I can call methods OK though. But not access fields. I get random garbage values instead of what I am expecting.
Here is my Java code:
private class MYView extends View {
public MYView(Context context) { super(context); five = 555; }
public int five;
....
}
C++ part:
jobject view = (jobject) Env->CallObjectMethod(Obj, jfindViewById, 3);
ClassMYView = Env->GetObjectClass(view);
jfieldID f = Env->GetFieldID(ClassMYView, "five", "I");
int i = Env->GetIntField(ClassMYView, f); <-- error is here, class is not object!
This is what I get after the C++ code executes
view = 0x40521b80
ClassMYView = 0x40521a70
f = 0x444727e4
i = 4390958 // supposed to be 555!
Please anybody with experience, what am I doing wrong?? Thank you.
The jclass instance is your object on which a method will be invoked; you'll need to look up the getName method ID on the Class class, then invoke it on the jclass instance using CallObjectMethod to obtain a jstring result. So in short yes, you just call the getName function and look at the jstring result.
Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface (JNI). JNA's design aims to provide native access in a natural way with a minimum of effort. Unlike JNI, no boilerplate or generated glue code is required.
jint GetVersion(JNIEnv *env); Returns the version of the native method interface.
jobject thiz means the this in java class. Sometimes if you create a static native method like this. void Java_MyClass_method1 (JNIEnv *, jclass); jclass means the class itself. Follow this answer to receive notifications.
Maybe you want to write
jobject obj = (jobject) Env->CallObjectMethod(Obj, jfindViewById, 3);
ClassMYView = Env->GetObjectClass(obj);
jfieldID f = Env->GetFieldID(ClassMYView, "five", "I");
int i = Env->GetIntField(obj, f);
The compiler doesn't give you an error because basically jobject and jclass are the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With