39555c89创建于 2025年12月19日历史提交

NativeVSync Development (C/C++)

Overview

The NativeVSync module is used to obtain the system VSync signal, create and destroy an OH_NativeVSync instance, and set the VSync callback function. When the VSync signal is triggered, the callback function is called.

Available APIs

API Description
OH_NativeVSync_Create (const char *name, unsigned int length) Creates an OH_NativeVSync instance. A new OH_NativeVSync instance is created each time this API is called. This function must be used in pair with OH_NativeVSync_Destroy. Otherwise, memory leak occurs.
OH_NativeVSync_Destroy (OH_NativeVSync *nativeVsync) Destroys an OH_NativeVSync instance.
OH_NativeVSync_FrameCallback (long long timestamp, void *data) Sets a callback function. timestamp indicates the timestamp, and data indicates a pointer to the input parameters of the callback function.
OH_NativeVSync_RequestFrame (OH_NativeVSync *nativeVsync, OH_NativeVSync_FrameCallback callback, void *data) Requests the next VSync signal. When the signal arrives, a callback function is invoked.

For details about the APIs, see native_vsync.

How to Develop

The following steps describe how to use the native APIs provided by NativeVSync to create and destroy an OH_NativeVSync instance and set the VSync callback function.

Adding Dynamic Link Libraries

Add the following library file to the CMakeLists.txt file.

libnative_vsync.so

Including Header Files

#include <native_vsync/native_vsync.h>
  1. Define a VSync callback function.

    void RenderEngine::OnVsync(long long timestamp, void *data)
    {
        OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_PRINT_DOMAIN, "RenderEngine", "OnVsync %{public}lld.", timestamp);
        auto renderEngine = reinterpret_cast<RenderEngine *>(data);
        if (renderEngine == nullptr) {
            return;
        }
    
        renderEngine->vSyncCnt_++;
        renderEngine->wakeUpCond_.notify_one();
    }
    
  2. Create an OH_NativeVSync instance.

    const char* demoName = "NativeImageSample";
    nativeVsync_ = OH_NativeVSync_Create(demoName, strlen(demoName));
    
  3. Set the VSync callback function through the OH_NativeVSync instance.

    wakeUpCond_.wait(lock, [this]() { return wakeUp_ || vSyncCnt_ > 0; });
    wakeUp_ = false;
    if (vSyncCnt_ > 0) {
        vSyncCnt_--;
        (void)OH_NativeVSync_RequestFrame(nativeVsync_, &RenderEngine::OnVsync, this);
        OH_NativeVSync_GetPeriod(nativeVsync_, &period);
    }
    
  4. Destroy the OH_NativeVSync instance.

    OH_NativeVSync_Destroy(nativeVsync_);
    nativeVsync_ = nullptr;