java到c对象传递

aamkag61  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(331)

我有一个调用内核模块的c代码,我想给它传递一个结构。这似乎是可行的ex-char设备捕捉多个(int)ioctl参数
不过,我是通过javajni调用c代码的。据说c结构Map是到java对象的。因此,我将一个对象传递给c本机函数。
这是我的jnic函数

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

我该如何接近?

kxxlusnw

kxxlusnw1#

必须手动复制对象中的字段。您可以调用jni方法来按名称获取字段的值。将字段本身传递到方法中可能比传递对象更容易。

xkftehaa

xkftehaa2#

您需要使用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规范以了解更多详细信息。

相关问题