HardCoder
HardCoder

Reputation: 3036

Can I create Bitmaps with the Android NDK in C++ and pass them to Java really fast?

I need to create Bitmaps in C++ with the ndk and pass them to Java. I don't mean copy but actually pass them as a parameter or return value or anything else like that because copying them would be far too slow. I also really need to create them in the NDK part and not in java.

Does anyone know a way to do that ?

Upvotes: 5

Views: 4122

Answers (3)

BitBank
BitBank

Reputation: 8715

I had the same issue and my solution was to allocate the huge buffer in C++ and then draw each requested "view" into a Java bitmap. I use the "new" NDK bitmap functions which showed up in Android 2.2; they allow direct access to the bitmap bits. It may not be ideal for your use, but it does avoid copying bitmaps and allow you to create bitmaps as large as free memory. I create a bitmap the size of the display window and then draw scaled views from the large bitmap into it with my own native code scaler.

Upvotes: 0

Robert
Robert

Reputation: 42585

As Peter Lawrey already pointed out using a non-Java object is not possible however it may be possible to directly paint the raw data from a simple Java byte array (which can be directly accessed on the C++ side).

In the end you could even call Canvas.drawBitmap(..) using this byte array for painting your created image. Of course that requires to store the image on C++ side directly in the required format inside the byte array.

Java:

byte[] pixelBuf = new byte[bufSize];

Then pass the byte[] reference to the native C++ implementation. On C++ side you can call

C++:

jbyte* pixelBufPtr = env->GetByteArrayElements(pixelBuf, JNI_FALSE);
jsize pixelBufLen = env->GetArrayLength(env, pixelBuf);
// modify the data at pixelBufPtr with C++ functions
env->ReleaseByteArrayElements(pixelBuf, pixelBufPtr, 0);

Upvotes: 7

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can try using a direct ByteBuffer. A ByteBuffer referes to a native area of memory. However to use the Image in Java it has to be in a Java object. You can assemble this object in Java or C, but I don't see how you can avoid copying the image unless your C library writes the image as the Java structure.

Upvotes: 1

Related Questions