How to pass a complex structure between C and Java with JNI on Android NDK

半世苍凉 提交于 2019-11-28 21:39:20

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:

public static 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:

jclass complexClass = env->FindClass("/com/main/ComplexClass");
jmethod constructor = env->GetMethodId(complexClass, "<init>", "()com/main/ComplexClass"); //The name of constructor method is "<init>"
jobject instance = 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!