Issue
I'm passing window buffer from native side in android app to java side.
AndroidBitmapInfo info;
void saveBufferToBitmap(JNIEnv *env, ANativeWindow_Buffer *buffer, jobject bitmap) {
void *pixels;
LOGI(10, "saving buffer to bitmap");
if (AndroidBitmap_getInfo(env, bitmap, &info) < 0) {
LOGE(10, "Failed to get bitmap info");
return;
}
if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
LOGE(10, "Failed to lock pixles for bitmap");
return;
}
int i, scan_length;
scan_length = buffer->width * 4;
memcpy(pixels, buffer->bits, buffer->width * buffer->height * 4); // 4 = (rgba)
AndroidBitmap_unlockPixels(env, bitmap);
//free(pixels); // here
}
Should i free pixels buffer in // here ? Does AndroidBitmap_lockPixels/AndroidBitmap_unlockPixels copy buffer to bitmap?
Solution
As a general rule you generally should never free a pointer that you did not create with new yourself. The library call you get the pointer from may use whatever allocation or just pass out a pointer to an internal data structure. The second is very likely in this case.
Looking at the documentation from the source:
/**
* Given a java bitmap object, attempt to lock the pixel address.
* Locking will ensure that the memory for the pixels will not move
* until the unlockPixels call, and ensure that, if the pixels had been
* previously purged, they will have been restored.
*
* If this call succeeds, it must be balanced by a call to
* AndroidBitmap_unlockPixels, after which time the address of the pixels should
* no longer be used.
*
* If this succeeds, *addrPtr will be set to the pixel address. If the call
* fails, addrPtr will be ignored.
*/
int AndroidBitmap_lockPixels(JNIEnv* env, jobject jbitmap, void** addrPtr);
Source: https://android.googlesource.com/platform/frameworks/native/+/master/include/android/bitmap.h
That tells us not do anything with pixels after AndroidBitmap_unlockPixels and definitely not free it.
Answered By - HHK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.