繁体   English   中英

从 JNI 访问 Java class object 方法

[英]Access Java class object methos from JNI

我有一个 Android 应用程序,我在 C++ 代码中实现了与 WebSocket 的连接。

现在我想调用一个 object 的方法,在 Java class 中初始化,通过 C++ 代码和 JNI。

有可能做到吗?

这是我的活动:

public class MainActivity extends AppCompatActivity{

private MyCustomObject object; //This object is initialized in the life cycle of the activty

}

我想要做的是从 JNI 调用object.myCustomMethod()

我试图为您的用例放置部分代码。

  1. onCreate期间将自定义 object 传递给JNI

     //MainActivity.java public class MainActivity extends AppCompatActivity { // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); } private MyCustomObject object; protected void onCreate(Bundle savedInstanceState) { object = new MyCustomObject(); //object is passed tthrough JNI call intJNI(object); } public class MyCustomObject{ public void myCustomMethod(){ } } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ public native void intJNI(MyCustomObject obj); }
  2. 在本机端,您保留 object 的引用并在适当的时间调用它

    //JNI static jobject globlaRefMyCustomObject; static JavaVM *jvm; extern "C" JNIEXPORT void JNICALL Java_test_com_myapplication_MainActivity_intJNI( JNIEnv* env, jobject callingObject, jobject myCustomObject) { jint rs = env->GetJavaVM(&jvm); assert (rs == JNI_OK); //take the global reference of the object globlaRefMyCustomObject = env->NewGlobalRef(myCustomObject); } //this is done in any background thread in JNI void callJavaCallbackFucntion(){ JNIEnv *env; jint rs = jvm->AttachCurrentThread(&env, NULL); assert (rs == JNI_OK); jclass MyCustomObjectClass = env->GetObjectClass(globlaRefMyCustomObject); jmethodID midMyCustomMethod = env->GetMethodID(MyCustomObjectClass, "myCustomMethod", "()V"); env->CallVoidMethod(globlaRefMyCustomObject,midMyCustomMethod); /* end useful code */ jvm->DetachCurrentThread(); } //Release the Global refence at appropriate time void JNI_OnUnload(JavaVM *vm, void *reserved){ JNIEnv* env; if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);= JNI_OK) { return JNI_ERR; } env->DeleteGlobalRef(globlaRefMyCustomObject); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM