简体   繁体   English

从C ++ JNI获取Java类中的实例变量

[英]get an Instance Variable in a Java class from C++ JNI

Good day, Sorry am just a noob in JNI so bear with me if it is a rather silly question :D now For calling a method in a java class from C++ using JNI, you can do this: 美好的一天,对不起,JNI只是一个菜鸟,如果这是一个愚蠢的问题,请多多包涵:DD要使用JNI从C ++调用Java类中的方法,可以这样做:

Java class: Java类:

public int getCount() {     
    return mCount; 
}

JNI: JNI:

JNIEXPORT void JNICALL
Java_com_example_init(JNIEnv* env, jobject obj, jint number)
{
    ...
    jclass Class = env->GetObjectClass(obj);
    jmethodID getCountMethodID = env->GetMethodID(Class,
                                                    "getCount", "()I");
    if (getCountMethodID == 0)
    {
        LOG("Function getCount() not found.");
        return;
    }
   Count = env->CallIntMethod(obj, getCountMethodID);
    ...
}

but how do you just get the instance variable from the java class directly? 但是如何直接从java类中获取实例变量呢? cannot seem to find an example for this. 似乎无法为此找到一个例子。 or is it very straightforward? 还是很简单?

You can refer the JNI Docs for more details http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp16536 . 您可以参考JNI文档以获取更多详细信息http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp16536

Get the jfieldID of the desired instance variable from jclass using following method 使用以下方法从jclass获取所需实例变量的jfieldID

jfieldID GetFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

Once you have the jfieldID you can access object instance variable using following method. 获得jfieldID后,您可以使用以下方法访问对象实例变量。 But you need to know upfront the type of field that you are going to access. 但是,您需要预先知道要访问的字段类型。

NativeType Get<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID);

You use GetFieldID() to get the field ID; 您可以使用GetFieldID()获取字段ID。 if you're going to be doing this multiple times or on multiple objects, be sure to cache that field ID instead of looking it up every time. 如果要多次执行此操作或对多个对象执行此操作,请确保缓存该字段ID,而不是每次都查找它。 Then, use the Get<type>Field() functions to get the field's value: 然后,使用Get<type>Field()函数获取字段的值:

jfieldID field = env->GetFieldID(Class, "myCount", "I");  // "I" = int field
if (field == NULL)
    /* Handle error */;

jint myCount = env->GetIntField(obj, field);
// Use field value...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM