0

I have a code which needs to be run from C (uses C library, plus it's performance is crticial and involves tons of loop iterations). The code needs to decode an image and run some operations on it. Final result should be Android/Java's bitmap.

Due to high resolution and a need to display a picture without any scaling this creates performacne issue.

I have pre-allocated bitmaps which I'm reusing, to avoid too many allocations and garbage collections. Currently I've managed to do all stuff required for proof of concept, I've done it like this:

public static void fillNativeBitmap(String src, Bitmap bmp) {
    byte[] nativeBytes = getNativeBytesARGB8(src);
    bmp.copyPixelsFromBuffer(ByteBuffer.wrap(nativeBytes));
}

JNIEXPORT jbyteArray JNICALL
notImportantForQuestion_getNativeBytesARGB8(
  JNIEnv *env,
  jclass clazz,
  jstring src
) {
    char *src_file;
    unsigned char *imptr;
    src_file = (*env)->GetStringUTFChars(env, src, NULL);
    const int total_pixels = xxx;
    static unsigned char mptr[xxx];
    decodeOneStep(src_file, &imptr); //uses lodepng to decode bitmap file
    
    doStuffWithImage(imptr, mptr);

    jbyteArray result = (*env)->NewByteArray(env, total_pixels); //here - unnececeary allocation for GC?

    (*env)->SetByteArrayRegion(env, result, 0, total_pixels, mptr);
    (*env)->ReleaseStringUTFChars(env, src, src_file);
    free(imptr); //I can live with that

    return result;
}

I'd like to reuse Java's bitmap buffer, pass it to C and fill it there. However, method for accessing java's array from C takes pointer to "isCopy". Accessing copy of Java's array does not work for me at all, as I don't need java's data from C context, I just need C context to fill Java's data.

What method should I use in this case? How to achieve it in most optimal way? I'm trying to optimise for performance and stability, the later one includes keeping number of allocations as low as possible.

7
  • Hi, welcome to SO. If I understand correctly, you want to pass a java array to your C code and then use the filled array in java? Commented Dec 21, 2020 at 9:42
  • Yes, I've found a sample way to do it: stackoverflow.com/questions/24649808/… But that method seems unsuitable, because of pointer to "isCopy" Commented Dec 21, 2020 at 9:55
  • Take a look at this post: stackoverflow.com/questions/5231599/… Commented Dec 21, 2020 at 9:57
  • Thanks a lot! Looks like it should solve my issue! Commented Dec 21, 2020 at 10:13
  • If you want direct access to the Bitmap's pixels then perhaps you should use the native AndroidBitmap functions. Commented Dec 21, 2020 at 10:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.