如何通过JNI将Struct从C传递回Java

时间:2018-05-14 22:35:04

标签: java android c java-native-interface

我有C struct

struct MyEntity {

    char *_myEntityType;

};

我创建了它的一个实例:

struct MyEntity my_C_Entity()
{

    struct MyEntity myEntity;

    myEntity . _myEntityType = strdup("user");

    return myEntity;

}

我想在Java中获得struct MyEntity my_C_Entity

Java MyEntity对象类

public class MyEntity {

    private String _myEntityType;

    public String get_myEntityType() {
        return _myEntityType;
    }

    public void set_myEntityType(String _myEntityType) {
        _myEntityType = _myEntityType;
    }
}  

然后......

public class FromCPP {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    public native  MyEntity _main();
}  

如何在MyEntity的结构struct MyEntity中设置my_C_Entity个对象成员?

extern "C"
JNIEXPORT jobject JNICALL
Java_myproject_1_FromCPP__1main(JNIEnv *env, jobject instance) {

    // set the values here
}

1 个答案:

答案 0 :(得分:3)

可以这样做:

jclass ent_clazz = env->FindClass("com/your/package/MyEntity");
if (!ent_clazz) return NULL;

// Get the IDs of the constructor and the _myEntityType field
jmethodID ent_init = env->GetMethodID(ent_clazz, "<init>", "()V");
jfieldID fid = env->GetFieldID(ent_clazz, "_myEntityType", "Ljava/lang/String;");
if (!ent_init || !fid) return NULL;

// Create a Java MyEntity instance
jobject result = env->NewObject(ent_clazz, ent_init);
if (!result || env->ExceptionCheck() != JNI_FALSE) {
    env->ExceptionClear();
    return NULL;
}

// entity is your C MyEntity instance
jstring jstr = env->NewStringUTF(entity._myEntityType);
if (!jstr || env->ExceptionCheck() != JNI_FALSE) {
    env->ExceptionClear();
    return NULL;
}

// Set the String field
env->SetObjectField(result, fid, jstr);

return result;

如果您为Java MyEntity类添加了一个带有_myEntityType初始值的构造函数,则可以创建该对象并在一个步骤中初始化该字段,这样就不需要{{ 1}}和GetFieldID