java到c对象传递

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

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

  1. JNIEXPORT jint JNICALL Java_com_context_test_ModCallLib_reNice
  2. (JNIEnv *env, jclass clazz, jobject obj){
  3. // convert objcet to struct
  4. // call module through IOCTL passing struct as the parameter
  5. }

如何从obj获取结构?
编辑:这是我要传递的对象,

  1. class Nice{
  2. int[] pids;
  3. int niceVal;
  4. Nice(List<Integer> pID, int n){
  5. pids = new int[pID.size()];
  6. for (int i=0; i < pids.length; i++)
  7. {
  8. pids[i] = pID.get(i).intValue();
  9. }
  10. niceVal = n;
  11. }
  12. }

我想要的结构是,

  1. struct mesg {
  2. int pids[size_of_pids];
  3. int niceVal;
  4. };

我该如何接近?

kxxlusnw

kxxlusnw1#

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

xkftehaa

xkftehaa2#

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

  1. //access field s in the object
  2. jfieldID fid = (env)->GetFieldID(clazz, "s", "Ljava/lang/String;");
  3. if (fid == NULL) {
  4. return; /* failed to find the field */
  5. }
  6. jstring jstr = (env)->GetObjectField(obj, fid);
  7. jboolean iscopy;
  8. const char *str = (env)->GetStringUTFChars(jstr, &iscopy);
  9. if (str == NULL) {
  10. return; // usually this means out of memory
  11. }
  12. //use your string
  13. ...
  14. (env)->ReleaseStringUTFChars(jstr, str);
  15. ...
  16. //access integer field val in the object
  17. jfieldID ifld = (env)->GetFieldID(clazz, "val", "I");
  18. if (ifld == NULL) {
  19. return; /* failed to find the field */
  20. }
  21. jint ival = env->GetIntField(obj, ifld);
  22. int value = (int)ival;

中有成员函数 JNIEnv 类来执行任何您需要的操作:读取和修改类的成员变量,调用方法,甚至创建新类。请查看jni规范以了解更多详细信息。

展开查看全部

相关问题