gpt4 book ai didi

java - 如何通过 JNI 将结构从 C 传回 Java

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:41 25 4
gpt4 key购买 nike

我有一个C结构:

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();
}

如何从 my_C_Entity 中的 Struct struct MyEntity 设置 MyEntity 的对象成员?

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

// set the values here
}

最佳答案

可以这样做:

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 的初始值,您可以一步创建对象并初始化字段,这将不再需要 GetFieldIDSetObjectField

关于java - 如何通过 JNI 将结构从 C 传回 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com