as the title already says, I need to convert an int[] to a ByteBuffer in Java. Is there a recommended way to do this ?
I want to pass the ByteBuffer over JNI to C++. What do I have to look out for regarding any specific endian conversions in this case ?
Edit: Sorry, I mistakenly wrote ByteArray but meant the type ByteBuffer.
Edit: Sample code:
I stripped out the unnecessary parts. I call a Java function over JNI from c++ to load a resource and pass it back to c++ as bytebuffer. It works with various other resources. Now I have an “int []” and would like to know if there is an elegant way to convert it to a bytebuffer or if I have to go the oldfashioned way and fill it in a for loop.
ByteBuffer resource= null;
resource = ByteBuffer.allocateDirect((x*y+2)*4).order(ByteOrder.nativeOrder());
.
.
ByteBuffer GetResourcePNG(String text)
{
.
.
int [] pix;
map.getPixels(pix,0,x,0,0,x,y);
return resource;
}
You have to use
ByteBuffer.allocateDirectif you want to be able to use JNI’sGetDirectBufferAddress.Use
ByteBuffer.order(ByteOrder.nativeOrder())to adjust theByteBufferinstance’s endianness to match the current platform.After the
ByteBuffer‘s endianness is properly configured, useByteBuffer.asIntBuffer()to get a view of it as ajava.nio.IntBufferand fill it with your data.Full Example: