Passing java.nio.IntBuffer to C function in an Android game

前端 未结 1 1339
广开言路
广开言路 2021-01-14 04:30

I\'d like to be able to add a little native C code in my Android app. I have an IntBuffer which I use as a parameter to OpenGL\'s glColorPointer method. This is populated/

相关标签:
1条回答
  • 2021-01-14 05:01

    Answering my own question here, it appears the answer is to take your array of vertices (which you're manipulating each frame using Java) and write them into a Direct Buffer.

    In my example above, I'd want to somehow populate the Direct Buffer mColourBuffer each frame with whatever is in the local array 'colours'. Turns out you'd want something like:

    JNIfastPutf(mfColourBuffer, colours, nCount); 
    

    where nCount is the number of bytes to copy. The (Native, C) function JNIfastPutf looks like this:

    void Java_com_a_b_c_JNIfastPutf(JNIEnv* env, jobject thiz, jobject jo, jfloatArray jfa, int n)
    {
        float* pDst = (float*) (*env)->GetDirectBufferAddress(env, jo);
        float* pSrc = (float*) (*env)->GetPrimitiveArrayCritical(env, jfa, 0);              
        memcpy( pDst, pSrc, n  );
    
       (*env)->ReleasePrimitiveArrayCritical(env, jfa, pSrc, 0);
    }
    

    I found the following link very helpful (my function is a slightly modified C version of their C++ example):

    http://www.badlogicgames.com/wiki/index.php/Direct_Bulk_FloatBuffer.put_is_slow

    They explain that you really need this sort of approach if you're working with floats; using ints is supposedly much faster, although that's where I started, and in any event, their native code shows in the region of a 20 -> 100% speed increase over the 'fast' int version, so there would appear to be little reason not to do it!

    0 讨论(0)
提交回复
热议问题