我将android app中原生端的窗口缓冲区传递给java端。
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
}
我应该在// here
中释放像素缓冲区吗? AndroidBitmap_lockPixels / AndroidBitmap_unlockPixels是否将缓冲区复制到位图?
答案 0 :(得分:0)
作为一般规则,您通常不应该free
自己没有使用new
创建的指针。库调用你得到指针可以使用任何分配或只是传递指向内部数据结构的指针。在这种情况下,第二种情况很可能。
查看来源的文档:
/**
* 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);
来源:https://android.googlesource.com/platform/frameworks/native/+/master/include/android/bitmap.h
这告诉我们在AndroidBitmap_unlockPixels之后没有对pixels
做任何事情,绝对不是free
。