Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 540
HardCoder Avatar asked Dec 17 '11 13:12

HardCoder


2 Answers

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);
like image 155
Robert Avatar answered Sep 20 '22 19:09

Robert


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.

like image 35
Peter Lawrey Avatar answered Sep 16 '22 19:09

Peter Lawrey