Wednesday, June 2, 2010

Java NIO ByteOrdering with JNA and native C code on OSX

Say you want to interact with a C program that modifies a NIO Buffer allocated from Java. Java NIO provides a way to help with this but the default ByteOrder on NIO ByteBuffers is BigEndian. By allocating the buffer with the same ordering using ByteOrder.nativeOrder(), a mismatch will not occur between native and JVM code.

Example Java class:
...
public class JNAByteOrderExample {
public static void main(String[] args)
{
FloatBuffer fb = ByteBuffer.allocateDirect(10*4).order(ByteOrder.nativeOrder()).asFloatBuffer();

for(int index =0; index<...)
{
System.out.print( " " + data.get(index) );
}

static
{
Native.register("/libdemo.dylib");
}
public static native int demo(FloatBuffer fb);
}

Example C code:

int demo( float * data )
{
int i = 0;
for( i = 0; i ...)
{
data[i]=777;
}
return 0;
}

Compile the C file with:
gcc -bundle -o libdemo.dylib -dynamic demo.c

No comments:

Post a Comment