JNI / C library: ptr byte traversal

I have unsigned char*C in my library and I call a JNI-exported function, which should set a java object with this data, preferably in byte[].

But this function will be called very often, and there is a lot of data to copy.

Can I use a ByteBuffer and assign the pointer of this ByteBuffer to mine unsigned char*? Or does it work just the opposite?

Can I do this without copying the data? What would be the best way to access it?

Known data size in unsigned char*.

+3
source share
1 answer

Here is a possible solution, given the little information you gave.

Java :

package com.stackoverflow;

public class JNIQuestion
{
  static native void fillByteArray(byte[] buffer);
}

C :

JNIEXPORT void JNICALL Java_com_stackoverflow_JNIQuestion_fillByteArray(JNIEnv* env, jbyteArray array)
{
  jboolean isCopy;
  jbyte* buffer = (*env)->GetByteArrayElements(env, array, &isCopy);
  jsize length = (*env)->GetArrayLength(env, array);
  jsize i;

  // do something with the buffer here, replace with something meaningful
  // PAY ATTENTION TO BUFFER OVERFLOW, DO NOT WRITE BEYOND BUFFER LENGTH
  for (i = 0; i < length; ++i)
    buffer[i] = i;

  // here it is important to use 0 so that JNI takes care of copying
  // the data back to the Java side in case GetByteArrayElements returned a copy
  (*env)->ReleaseByteArrayElements(env, buffer, 0);
}

ByteBuffer (ByteBuffer.allocateDirect()) . ByteBuffer, Java .

, byte[] , JVM , GetByteArrayElements().

, JNI, , C Java C .

, .

PS: , . JNI Guide JNI Tutorial.

+4

Source: https://habr.com/ru/post/1724770/


All Articles