gpt4 book ai didi

Java 到 C 对象传递

转载 作者:行者123 更新时间:2023-11-30 11:41:49 25 4
gpt4 key购买 nike

我有调用内核模块的 C 代码,我想将一个结构传递给它。这似乎是可行的前 - char device catch multiple (int) ioctl-arguments

不过,我是通过 java JNI 调用 c 代码的。据说 C 结构映射是到 Java 对象。所以我将一个对象传递给 C native 函数。

这是我的 JNI c 函数

  JNIEXPORT jint JNICALL Java_com_context_test_ModCallLib_reNice
(JNIEnv *env, jclass clazz, jobject obj){

// convert objcet to struct
// call module through IOCTL passing struct as the parameter
}

我应该如何从 obj 获取结构体?

编辑:这是我传递的对象,

class Nice{

int[] pids;
int niceVal;

Nice(List<Integer> pID, int n){
pids = new int[pID.size()];
for (int i=0; i < pids.length; i++)
{
pids[i] = pID.get(i).intValue();
}
niceVal = n;
}
}

我想要的结构是这样的,

struct mesg {
int pids[size_of_pids];
int niceVal;
};

我应该如何处理?

最佳答案

您将需要使用 JNI 方法来访问字段,例如:

//access field s in the object
jfieldID fid = (env)->GetFieldID(clazz, "s", "Ljava/lang/String;");
if (fid == NULL) {
return; /* failed to find the field */
}

jstring jstr = (env)->GetObjectField(obj, fid);
jboolean iscopy;
const char *str = (env)->GetStringUTFChars(jstr, &iscopy);
if (str == NULL) {
return; // usually this means out of memory
}

//use your string
...

(env)->ReleaseStringUTFChars(jstr, str);

...

//access integer field val in the object
jfieldID ifld = (env)->GetFieldID(clazz, "val", "I");
if (ifld == NULL) {
return; /* failed to find the field */
}
jint ival = env->GetIntField(obj, ifld);
int value = (int)ival;

JNIEnv 类中有成员函数可以执行您需要的任何操作:读取和修改类的成员变量、调用方法甚至创建新类。看看 JNI Specifications了解更多详情。

关于Java 到 C 对象传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12110876/

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