Call OH_NativeWindow_DestroyNativeWindowBuffer() in a timely manner after use to release the native window buffer created via OH_NativeWindow_CreateNativeBufferFromNativeBuffer() or OH_NativeWindow_CreateNativeBufferFromSurfaceBuffer(). Otherwise, the buffer resources cannot be reclaimed, causing memory leaks.
// rules.json
{
"rules": {
"cpp": {
"ResourceLeak": [
{
"ruleId": "NativeWindowBuffer API Not Paired",
"severity": "error",
"skip": false
}
]
}
}
} // Positive example
#include "native_window/external_window.h"
void ProcessBufferFromSurfaceWithDestroy(void *surfaceBuffer)
{
OHNativeWindowBuffer *buffer = OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer(surfaceBuffer);
if (buffer == nullptr) {
return;
}
// Use the buffer for processing...
// Properly destroy the buffer.
OH_NativeWindow_DestroyNativeWindowBuffer(buffer);
}
void ProcessBufferFromNativeWithDestroy2(OH_NativeBuffer* nativeBuffer)
{
OHNativeWindowBuffer *buffer = OH_NativeWindow_CreateNativeWindowBufferFromNativeBuffer(nativeBuffer);
if (buffer == nullptr) {
return;
}
// Use the buffer for processing...
// Properly destroy the buffer.
OH_NativeWindow_DestroyNativeWindowBuffer(buffer);
} // Negative example
#include "native_window/external_window.h"
void ProcessBufferWithoutDestroy(void *surfaceBuffer)
{
// Create a native window buffer from a surface buffer.
OHNativeWindowBuffer *buffer = OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer(surfaceBuffer);
if (buffer == nullptr) {
return;
}
// Use the buffer.
// Not released - memory leak!
} For details about how to configure Code Scanner check rules, see Using codescanner.