Search code examples
javaandroidstructjava-native-interfaceioctl

Java to C object passing


I have C code that call a kernel module and I want to pass a struct to it. This seems doable ex - char device catch multiple (int) ioctl-arguments

However I am invoking the c code through java JNI. It was said C struct mapping is to Java object. so am passing an object to the C native function.

Here is my JNI c function

  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
  }

How should I get a struct from obj?

EDIT: here is the object that I am passing,

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

the struct I want to have is this,

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

How should I approach?


Solution

  • You will need to use JNI methods to access the fields, for example:

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

    There are member functions in the JNIEnv class to do whatever you need: to read and modify member variables of the class, to invoke methods and even to create new classes. Have a look at the JNI Specifications for more details.