目录

Creating and Destroying a Critical Scope and Accessing String Content Using Node-API Extension APIs

The Node-API extension APIs napi_open_critical_scope and napi_close_critical_scope are used to open and close a critical scope, respectively.

Non-critical APIs cannot be used within a critical scope, and only one critical scope can be opened in the same execution environment. Opening a critical scope blocks GC. Keeping a critical scope open for a long time may cause issues such as memory shortage and lag. It is recommended that a critical scope be opened only when critical APIs are needed and closed promptly after use.

When to Use

Before calling critical APIs, you must open a critical scope using napi_open_critical_scope and call the APIs in the critical scope.

After the critical scope is closed, do not use the critical API or its return result. Otherwise, the program may crash or data may be damaged.

Opening and Closing a Critical Scope and Using Critical APIs

API Description Status Code for Executions Outside the Critical Scope
napi_open_critical_scope Opens a critical scope. NA
napi_close_critical_scope Closes a critical scope. napi_generic_failure
napi_get_buffer_string_utf16_in_critical_scope Obtains the UTF-16 encoding memory buffer data of an ArkTS string. napi_generic_failure
  1. Only when an ArkTS string is stored in UTF-16 encoding can napi_get_buffer_string_utf16_in_critical_scope correctly obtain its memory buffer; otherwise, the function returns an error.

  2. napi_create_string_utf16 and napi_create_string_utf8 are used to pass the input data to the VM in the specified encoding format. These functions do not control the internal storage encoding format of strings in the VM.

Sample Code