xcesco
xcesco

Reputation: 4838

NDK, work with FloatBuffer as parameter

I'm working with NDK and native buffer. I have the following code:

Java class definition with native method:

public class MyNDK {

    static {
        System.loadLibrary("MyLibrary");
    }

    public native void workWithFloatBuffer(FloatBuffer buffer, int base, int size);

}

Native code implementation (i have test its definition and it's ok):

JNIEXPORT void JNICALL Java_com_example_xcesco_myapplication_MyNDK_workWithFloatBuffer(JNIEnv *env, jobject object, jobject input, jint base, jint size)
{
    jfloat *buffer =(jfloat *) env->GetDirectBufferAddress(input);

    for (int i=base;i<size;i++)
    {
        buffer[i]=i*2.0f;
    }
}

And the code used in an activity to test the result:

    FloatBuffer buffer= ByteBuffer.allocateDirect(4*10).asFloatBuffer();
    (new MyNDK()).workWithFloatBuffer(buffer, 0,4);

    for (int i=0; i< 4;i++) {
        Log.i("BLA", "value["+i+"]="+buffer.get(i));
    }

Current result on log is:

value[0]=0.0
value[1]=9.0E-44
value[2]=4.6007E-41
value[3]=6.8966E-41

That's very different from the aspected result of

value[0]=0.0
value[1]=2
value[2]=4
value[3]=6

What's it wrong?

Upvotes: 0

Views: 1060

Answers (1)

Michael
Michael

Reputation: 58467

Looking at the values in a float converter was informative:

9.0E-44 equals 0x00000040
4.6007E-41 equals 0x00008040

2.0 equals 0x40000000
4.0 equals 0x40800000

So what you've got here is an endianness problem. You could try declaring your FloatBuffer as follows:

FloatBuffer buffer = ByteBuffer.allocateDirect(16)
                               .order(ByteOrder.LITTLE_ENDIAN)
                               .asFloatBuffer();

Or you could reversing the endianness of the values in your C++ code if you prefer that.

Upvotes: 2

Related Questions