jni not support types as void*, unsigned int*, … What to do?

前端 未结 4 522
失恋的感觉
失恋的感觉 2021-01-13 22:46

I have .so (shared library) written in C++, lets call it functionality.so in which I implement different functions, here is list of some fu

4条回答
  •  甜味超标
    2021-01-13 23:13

    What you want to do is this: For the void* function, use direct byte buffers. On the Java side:

    native long initialize(java.nio.ByteBuffer userData);
    

    When you call the method, make sure to allocate a direct ByteBuffer (see java.nio.ByteBuffer, and JNI nio usage):

    ByteBuffer myData = ByteBuffer.allocateDirect(size);
    long res = initialize(myData);
    

    On the C side, you do this:

    unsigned long res = Initialize(env->GetDirectBufferAddress(env, buffer));
    return (jlong)res;
    

    You read and write from the buffer on the Java side with the ByteBuffer methods.

    You can also allocate the byte buffer on the C side with env->NewDirectByteBuffer(env, ptr, size.

    Now, for the second function, I assume the unsigned long* argument is used to return a result. You can use the same approach (direct ByteBuffers), but I would recommend a different one that wouldn't entail allocating a buffer for such a small value.

    On the Java side:

    native long deviceOpen(long id, long[] device);
    

    On the C side:

    unsigned long c_device;
    unsigned long res = DeviceOpen((unsigned long)j_id, &c_device);
    env->SetLongArrayRegion(env, j_device, 0, 1, &c_device);
    return (jlong)res;
    

    Then you call the method from Java:

    long[] deviceOut = new long[1];
    long res = deviceOpen(id, deviceOut);
    long device = deviceOut[0];
    

    For more information on array access from JNI see JNI array operations

提交回复
热议问题