如何通过JNI设置Java类的Double / Integer类型的值

时间:2016-01-18 06:38:50

标签: java android c++ java-native-interface

早些时候,我问一个问题:

How can I set the value of “Double” type variable of my Class by JNI?

但是,我没有得到我想要的正确答案。 假设我有一个类似的类:

class Data
{
    public Integer value;
}

本机:

public static native int testGet(Data tdobj);

c代码:

JNIEXPORT jint JNICALL
test_jni_Native_testSet(JNIEnv *env, jclass type, jobject tdobj)
{
    jclass tdobjClass = env->FindClass("xxxx/Data");
    jfieldID valueID = env->GetFieldID(tdobjClass, "value", "Ljava/lang/Integer;");
    env->SetIntField(tdobj, jValueID, 123);
    return 0;
}

当我调用Native.testGet时,程序崩溃了,并显示错误消息如下:

E/dalvikvm: JNI ERROR (app bug): accessed stale weak global reference 0x7b (index 30 in a table of size 6)
E/dalvikvm: VM aborting
Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 26758 

我真的不知道

如何处理类中的Double / Integer类型,它看起来与String类型相同,但它与String类型不同。似乎这样的类型可以由jobject处理,但结果让我感到困惑。

感谢。

我不想使用像double / int这样的原始类型来实现我的目标,而且我也不想使用函数。或者您可以告诉我,我希望的方式无法实现我的目标。非常感谢~~

1 个答案:

答案 0 :(得分:1)

首先,当你从value实例获得Data字段时,它没有被初始化,正如你的java代码所示,所以需要创建一个实例。

其次,您无法更改整数值,您必须使用所需的值对其进行实例化。因此,创建一个新的Integer,然后从value实例更改Data字段。像这样:

JNIEXPORT jint JNICALL test_jni_Native_testSet(JNIEnv *env, jclass type, jobject tdobj)
{
    //Create Integer class, get constructor and create Integer object
    jclass intClass = env->FindClass(env, "java/lang/Integer");
    jmethodID initInt = env->GetMethodID(env, intClass, "<init>", "(I)V");
    if (NULL == initInt) return -1;
        jobject newIntObj = env->NewObject(env, intClass, initInt, 123);

    //Now set your integer into value atttribute. For this, I would
    //recommend you to have a java setter and call it in the same way 
    //as shown above

    //clean reference
    env->DeleteLocalRef(env, newIntObj); 
    return 0;
}