【发布时间】:2014-11-11 19:12:30
【问题描述】:
我正在尝试从 JNI 设置变量的值(java 中的变量)。
我正在使用GetFieldID 和SetIntField 来做同样的事情。
以下是我的代码。
main.c
JNIEXPORT void JNICALL Java_com_example_hello_MainActivity_samplefunc
(JNIEnv *env, jobject obj, jobject x)
{
jclass class = (*env)->GetObjectClass(env, x);
jfieldID fid = (*env)->GetFieldID(env, myclass,"a","I");
(*env)->SetIntField(env, obj ,fid, 10);
return;
}
MainActivity.java
package com.example.hello;
public class MainActivity extends ActionBarActivity
{
int a = -1;
/* Declaration of Native function & Load JNI Library*/
public static native void samplefunc(Class x);
static {
System.loadLibrary("hellojni");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Class x = this.getClass();
Log.d("JNI", "Before : Value of Port: " + a);
samplefunc(x);
Log.d("JNI", "After : Value of Port: " + a);
return;
}
}
预期的 Logcat 输出是:
D/JNI Before : Value of Port: -1
D/JNI After : Value of Port: 10
但我收到以下错误:
D/JNI (12607): Before : Value of Port: -1
W/dalvikvm(12607): JNI WARNING: JNI function SetIntField called with exception pending
W/dalvikvm(12607): in Lcom/example/hello/MainActivity;.samplefunc:(Ljava/lang/Class;)V (SetIntField)
W/dalvikvm(12607): Pending exception is:
I/dalvikvm(12607): java.lang.NoSuchFieldError: no field with name='a' signature='I' in class Ljava/lang/Class;
I/dalvikvm(12607): at com.example.hello.MainActivity.samplefunc(Native Method)
我想这有点基本,但我是 JNI 的新手。
对此的任何帮助将不胜感激。
我已经看过了: JNI: NoSuchFieldError 但是它没有解释如何设置任何变量的值。
【问题讨论】:
标签: java android c android-ndk java-native-interface