I try to get the value in the Native class field mInt. This class is created by SimpleJNI.
In this sample I set the mInt value to 9. JNI function add try to get the mInt value by using GetIntField. It should return 9 in add function. But it seems GetIntfield cannot find the field in this jobject. How do I get the mInt from JNI? Thanks for your comment.
Here is the JNI source code.
static jfieldID gNative;
static jint add(JNIEnv *env, jobject thiz, jint a, jint b) {
int result = a + b;
LOGI("%d + %d = %d", a, b, result);
int value = env->GetIntField(thiz , gNative);
result = value;
return result;
}
static const char *classPathName = "com/example/android/simplejni/Native";
static JNINativeMethod methods[] = {
{"add", "(II)I", (void*)add },
};
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
LOGE("Native registration unable to find class '%s'", className);
return JNI_FALSE;
}
gNative = env->GetFieldID(clazz, "mInt" , "I");
if(gNative == NULL) {
LOGE("Get mInt field id fail");
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
LOGE("RegisterNatives failed for '%s'", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
static int registerNatives(JNIEnv* env)
{
if (!registerNativeMethods(env, classPathName,
methods, sizeof(methods) / sizeof(methods[0]))) {
return JNI_FALSE;
}
return JNI_TRUE;
}
typedef union {
JNIEnv* env;
void* venv;
} UnionJNIEnvToVoid;
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
UnionJNIEnvToVoid uenv;
uenv.venv = NULL;
jint result = -1;
JNIEnv* env = NULL;
LOGI("JNI_OnLoad");
if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed");
goto bail;
}
env = uenv.env;
if (registerNatives(env) != JNI_TRUE) {
LOGE("ERROR: registerNatives failed");
goto bail;
}
result = JNI_VERSION_1_4;
bail:
return result;
}
The Native class is here. public function setval is used to set mInt value in this class.
public class Native {
private int mInt;
static {
System.loadLibrary("simplejni");
}
public void setval(int k){
mInt = k;
}
static native int add(int a, int b);
}
SimpleJNI is code list as follow.
public class SimpleJNI extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
Native nv = new Native();
nv.setval(9);
int sum = nv.add(2, 3);
tv.setText("2 + 3 = " + Integer.toString(sum));
setContentView(tv);
}
}
I already found the root cause of why JNI add function cannot get value from GetIntField.
Because the native function declare cannot be static.
It should be