我有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
}
答案 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
。