How To Pass A Complex Structure Between C And Java With Jni On Android Ndk
Solution 1:
You cannot pass raw C structs into Java and expect it to treat these structs as classes. You need to create a class for your struct. I see you already did that, so the only thing you need to do is to convert this struct into an instance of the class.
The code on the Java side:
publicstatic native ComplexClass listenUDP();
will translate to:
JNIEXPORT jobject JNICALL Java_com_main_MainActivity_listenUDP(JNIEnv *env, jclass);
In that C code, you need to load the ComplexClass using the env->FindClass();
function. Then to create a new instance of that class (it simplifies matters if you have zero-parameter constructor), you need to load a constructor method signature and "invoke" it in the env->NewObject()
method. Full code:
jclasscomplexClass= env->FindClass("/com/main/ComplexClass");
jmethodconstructor= env->GetMethodId(complexClass, "<init>", "()com/main/ComplexClass"); //The name of constructor method is "<init>"jobjectinstance= env->NewObject(complexClass, constructor);
Then you need to set the fields of this class using env->setXXXField();
. If you have more objects as fields and want to alse create them, then repeat the above process for another object.
This looks very complicated, but that's the price for using native C in managed Java code.
Post a Comment for "How To Pass A Complex Structure Between C And Java With Jni On Android Ndk"