我必须在eclipse中使用JNI从我的c程序访问java程序中声明的变量

时间:2014-12-04 10:58:05

标签: java c eclipse android-ndk java-native-interface

这是我的java代码

package com.example.javacallinc;

import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
public class JNITest extends Activity {
static {
System.loadLibrary( "JNITest" );
}
private int i = 42;
public String s = "Written in Java";
public static double sd = 3.14;
//protected static String ss = "JNI - Java";
public native String modifyVariables();
@Override public void onCreate(Bundle b) {
super.onCreate(b);
TextView tv = new TextView(this);
String s = modifyVariables();
s += "After calling C code, variables are:\n";
s += "i = " + Integer.toString(i) + "\n";
s += "s = " + s + "\n";
s += "sd = " + sd + "\n";
//s += "ss = " + ss + "\n";
tv.setText(s);
setContentView(tv);
}
}

这是我的c代码

#include <stdio.h>
#include<string.h>
#include<jni.h>


jstring
Java_org_linaro_jnitest_JNITest_modifyVariables(JNIEnv*env, jobject *o) {
jclass thisClass = (*env)->GetObjectClass(env,o);
jfieldID id_i = (*env)->GetFieldID(env,thisClass, "i", "I");
jfieldID id_s = (*env)->GetFieldID(env,thisClass, "s", "Ljava/lang/String;");
jfieldID id_sd = (*env)->GetStaticFieldID(env,thisClass, "sd", "D");
jfieldID id_ss = (*env)->GetStaticFieldID(env,thisClass, "ss", "Ljava/lang/String;");
jint c_i = (*env)->GetIntField(env, thisClass, id_i);
jstring c_s = (jstring)(*env)->GetObjectField(env,thisClass, id_s);
jdouble c_sd = (*env)->GetStaticDoubleField(env,thisClass, id_sd);
jstring c_ss = (jstring)(*env)->GetStaticObjectField(env, thisClass, id_ss);
char *cs_s = (*env)->GetStringUTFChars(env, c_s, NULL);
char *cs_sd = (*env)->GetStringUTFChars(env, c_sd,NULL);
char buf[512];
snprintf(buf, 512, "Variables initially seen by C code:\ni=%u\ns=%s\nsd=%f\nss=%s\n\n", c_i, cs_s, c_sd,cs_ss);
(*env)->ReleaseStringUTFChars(env, c_s, cs_s);
(*env)->ReleaseStringUTFChars(env, c_ss, cs_ss);
(*env)->SetIntField(env, thisClass, id_i, 1701);
(*env)->SetObjectField(env, thisClass, id_s,
(*env)->NewStringUTF(env, "Written in C"));
(*env)->SetStaticDoubleField(env, thisClass,id_sd, 3.1415926);
(*env)->SetStaticObjectField(env, thisClass,id_ss, (*env)->NewStringUTF(env, "JNI - C"));
return (*env)->NewStringUTF(env, buf);
}

当我在eclipse中运行程序时,我收到这样的错误 -

java.lang.unstaisfiedlinkerror:native library not included.

我已将该库包含在Android.mk中。 请帮帮我......

2 个答案:

答案 0 :(得分:0)

在某种程度上,当你忽视它时,你正在呼唤一个不存在的图书馆。我不了解所有代码,但我建议您尝试查看代码可以调用的所有库是否都已导入。

答案 1 :(得分:0)

请发布您的Android.mk文件。还要确保为application.mk中指定的所有平台生成JNITest.so文件(默认情况下不存在,但您可以创建一个并指定APP_ABI:= all等参数,这意味着,将创建一个.so文件为每个平台)。默认情况下,您应该至少看到在jni文件夹中创建的arm文件夹,它应该包含相应的.so文件。