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?

Answers


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.


You have to manually copy the fields from the object. You can call JNI methods to get the value of the fields by name. It might be easier to pass the fields themselves into the method instead of passing an object.


Need Your Help

Heroku ZipImportError: bad local file header

heroku pip

I keep running into this strange Heroku build error. If I mess around with the ordering of my requirements.txt then the package that fails to build will change, but the build always ends with the

AngularJS[$injector:unpr] Unknown provider

angularjs error-handling angularjs-injector

Can somone offer me insight on why I am getting the error in the title based on my code? Not quite sure why.