I'm trying to pass a structure as a pointer from JNI to Java to be able to pass it back later from Java to JNI. I have read this thread: Passing pointers between C and Java through JNI, but I did not succeed.
I have a pretty complex structure : struct myStruct_s myStruct;
From Java, I call a JNI function to initialize the structure and to return a long (pointer to the structure):
JNIEXPORT jlong JNICALL Java_example_ExampleJNI_getStruct(JNIEnv *jenv, jclass jcls) {
struct myStruct_s mystruct;
long *lp = (long*)&myStruct;
return lp;
}
Then I call a Java method with that long in argument. In JNI I want to be able to use the strcuture created earlier. I do like this:
JNIEEXPORT jint JNICALL Java_example_ExampleJNI_methode1(JNIEnv *jenv, jclass jcls, jlong jarg) {
struct myStruct_s *arg = (struct myStruct_s *)&jarg;
...
}
Well it doesn't work. I guess my cast of the long into the struct is wrong. How should I do it? Thank you.
EDIT : Thanks for the hints, here are the working functions
JNIEXPORT jint JNICALL Java_example_ExampleJNI_methode1(JNIEnv *jenv, jclass jcls, jlong jarg) {
struct myStruct_s *arg;
arg = (struct myStruct_s *)jarg;
...
}
JNIEXPORT jlong JNICALL Java_example_ExampleJNI_getStruct(JNIEnv *jenv, jclass jcls) {
struct myStruct_s *myStruct;
myStruct = (struct myStruct_s *)malloc(sizeof(struct myStruct_s));
long lp = (long)myStruct;
return lp;
}