JNI - how to use multiple Jni wrapper instances with different fields?

后端 未结 2 457
有刺的猬
有刺的猬 2021-01-23 07:30

background

I have an android project that uses JNI (using NDK) to code in both Java and C/C++.

I\'ve created a Jni java wrapper on the java side that will do a

2条回答
  •  一整个雨季
    2021-01-23 08:08

    I've found a possible solution (link here), to either use a jlong or jobject to be a handle (or pointer, if you wish) to the object that was created on the JNI side.

    people said it's better to use a jobject as ByteBuffer instead of jlong for better compatibility.

    the solution is :

    Java side:

    private native ByteBuffer init();
    private native void foo(ByteBuffer handle);
    

    JNI side:

    /**a class to hold the fields*/
    class FieldsHolder
      {
      ... //private fields, for each instance
      }
    

    creating the JNI object and sending to java side:

    JNIEXPORT jobject JNICALL ...init(JNIEnv * env, jobject obj)
      {
      FieldsHolder* myClass= new FieldsHolder();
      ... //prepare fields of the class
      return env->NewDirectByteBuffer(myClass, 0);
      }
    

    re-using the JNI object :

    JNIEXPORT void JNICALL ...foo(JNIEnv * env, jobject obj, jobject handle)
      {
      FieldsHolder* myClass= (FieldsHolder*) env->GetDirectBufferAddress(handle);
      //now we can access the fields again.
      }
    

提交回复
热议问题