Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading integer field from Java object with C++ (JNI)

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.

like image 805
exebook Avatar asked Jun 11 '13 07:06

exebook


People also ask

What is Jclass in JNI?

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.

What is JNA vs JNI?

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.

What is JNIEnv * env?

jint GetVersion(JNIEnv *env); Returns the version of the native method interface.

What is JNI Jobject?

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.


1 Answers

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.

like image 137
spacifici Avatar answered Sep 20 '22 07:09

spacifici