Search code examples
javaandroidmemoryjava-native-interfacejavacpp

How to deal with JavaCPP avoiding data copy?


I'm using JavaCPP to exploit some C++ libraries in a Java application but manipulated datas are big datas. So my code works fine but is not memory-friendly (and I need it to work fast):

  • I have a big byte[][] to provide to the native part.
  • Target native function is something like nativeFunction(PointerPointer param) -> Doc
  • (To be precise, this is a PointerPointer<BytePointer> type expected, so a list of BytePointer as byte[][] is a list of byte[]) -> Doc

I initialize the expected param this way:

byte[][] myBigDatas;
// myBigDatas.length = 4
// myBigDatas[x].length = something like 4000000

// Initialize param
PointerPointer<BytePointer> srcParam = new PointerPointer<BytePointer>(
    myBigDatas[0],
    myBigDatas[1],
    myBigDatas[2],
    myBigDatas[3]);

// Call the native function
nativeFunction(srcParam);

Problem is, referring to documentation, for each BytePointer created by the call of PointerPointer<BytePointer>(...) with provided data, it's not a memory wrapping, but a copy that is made.

There is a way to avoid copy ?

EDIT:

Otherwise, does JNI provide solution for give AND return byte[][] WITHOUT COPYING IT? (I know it is for a simple byte[])


Solution

  • I found a solution, and just want to share it. I replaced my byte[][] with a ByteBuffer[] (an array of direct ByteBuffer). Then, doing

    BytePointer bp = new BytePointer(/*direct ByteBuffer*/)
    

    doesn't make copy! Performance gain is huge!!