• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Working with ArrayBuffer Using JSVM-API
2
3## Introduction
4
5**ArrayBuffer** in JavaScript (JS) is a type of object that represents a generic, fixed-length buffer of raw binary data. It provides a way to effectively represent and manipulate raw binary data in JS.
6
7## Basic Concepts
8
9- **ArrayBuffer**:
10
11  An **ArrayBuffer** object represents a generic, fixed-length buffer of raw binary data. The **ArrayBuffer** content cannot be directly operated. Instead, you need to use a **TypedArray** or **DataView** object to interpret the buffer data in specific formats. **ArrayBuffer** is used to process a large amount of binary data, such as files and network data packets.
12
13- Lifecycle and memory management:
14
15  When using **ArrayBuffer** with JSVM-API, pay special attention to lifecycle and memory management.
16
17## Available APIs
18
19| API                        | Description                                  |
20| ---------------------------- | ------------------------------------------ |
21| OH_JSVM_GetArraybufferInfo    | Obtains the underlying data buffer of an **ArrayBuffer** and its length. |
22| OH_JSVM_IsArraybuffer        | Checks whether a JS object is an **Arraybuffer** object.       |
23| OH_JSVM_DetachArraybuffer    | Calls the **Detach()** operation of an **ArrayBuffer** object.           |
24| OH_JSVM_IsDetachedArraybuffer | Checks whether an **ArrayBuffer** object has been detached.       |
25| OH_JSVM_CreateArraybuffer      | Creates an **ArrayBuffer** object of the specified size.  |
26
27## Example
28
29If you are just starting out with JSVM-API, see [JSVM-API Development Process](use-jsvm-process.md). The following demonstrates only the C++ and ArkTS code related to **ArrayBuffer** management.
30
31### OH_JSVM_GetArraybufferInfo
32
33Use **OH_JSVM_GetArraybufferInfo** to obtain the underlying data buffer of an **ArrayBuffer** object and its length.
34
35CPP code:
36
37```cpp
38// hello.cpp
39#include "napi/native_api.h"
40#include "ark_runtime/jsvm.h"
41#include <hilog/log.h>
42// Register the GetArraybufferInfo callback.
43static JSVM_CallbackStruct param[] = {
44    {.data = nullptr, .callback = GetArraybufferInfo},
45};
46static JSVM_CallbackStruct *method = param;
47// Set a property descriptor named getArraybufferInfo and associate it with a callback. This allows the GetArraybufferInfo callback to be called from JS.
48static JSVM_PropertyDescriptor descriptor[] = {
49    {"getArraybufferInfo", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
50};
51// Define OH_JSVM_GetArraybufferInfo.
52static JSVM_Value GetArraybufferInfo(JSVM_Env env, JSVM_CallbackInfo info)
53{
54    size_t argc = 1;
55    JSVM_Value args[1] = {nullptr};
56    // Parse the input parameters.
57    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
58    // Check whether the parameter is an ArrayBuffer object.
59    bool isArrayBuffer = false;
60    OH_JSVM_IsArraybuffer(env, args[0], &isArrayBuffer);
61    if (!isArrayBuffer) {
62        OH_LOG_ERROR(LOG_APP, "JSVM GetArraybufferInfo isArrayBuffer:false");
63    }
64    void *data;
65    size_t byteLength;
66    // Obtain the underlying data buffer and length of the ArrayBuffer object.
67    JSVM_Status status = OH_JSVM_GetArraybufferInfo(env, args[0], &data, &byteLength);
68    if (status != JSVM_OK) {
69        OH_LOG_ERROR(LOG_APP, "JSVM GetArraybufferInfo: failed");
70    } else {
71        OH_LOG_INFO(LOG_APP, "JSVM GetArraybufferInfo: success");
72    }
73    return args[0];
74}
75```
76
77JS code:
78
79```ts
80import hilog from "@ohos.hilog"
81// Import the native APIs.
82import napitest from "libentry.so"
83try {
84  // Pass the created ArrayBuffer object.
85  let script: string = `getArraybufferInfo(new ArrayBuffer(10))`;
86  let result = napitest.runJsVm(script);
87  hilog.info(0x0000, 'testJSVM', 'Test JSVM getArraybufferInfo : %{public}s', result);
88} catch (error) {
89  hilog.error(0x0000, 'testJSVM', 'Test JSVM getArraybufferInfo error: %{public}s', error.message);
90}
91```
92
93### OH_JSVM_IsArraybuffer
94
95Use **OH_JSVM_IsArraybuffer** to check whether a JS object is an **Arraybuffer** object.
96
97CPP code:
98
99```cpp
100// hello.cpp
101#include "napi/native_api.h"
102#include "ark_runtime/jsvm.h"
103#include <hilog/log.h>
104// Register the IsArrayBuffer callback.
105static JSVM_CallbackStruct param[] = {
106    {.data = nullptr, .callback = IsArrayBuffer},
107};
108static JSVM_CallbackStruct *method = param;
109// Set a property descriptor named isArrayBuffer and associate it with a callback. This allows the IsArrayBuffer callback to be called from JS.
110static JSVM_PropertyDescriptor descriptor[] = {
111    {"isArrayBuffer", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
112};
113// Define OH_JSVM_IsArraybuffer.
114static JSVM_Value IsArrayBuffer(JSVM_Env env, JSVM_CallbackInfo info)
115{
116    size_t argc = 1;
117    JSVM_Value args[1] = {nullptr};
118    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
119    // Call OH_JSVM_IsArraybuffer to check whether the input parameter is an ArrayBuffer object.
120    bool isArrayBuffer = false;
121    JSVM_Status status = OH_JSVM_IsArraybuffer(env, args[0], &isArrayBuffer);
122    if (status != JSVM_OK) {
123        OH_LOG_ERROR(LOG_APP, "JSVM IsArrayBuffer: failed");
124    } else {
125        OH_LOG_INFO(LOG_APP, "JSVM IsArrayBuffer: success");
126        OH_LOG_INFO(LOG_APP, "JSVM IsArrayBuffer: %{public}d", isArrayBuffer);
127    }
128    JSVM_Value boolean = nullptr;
129    OH_JSVM_GetBoolean(env, isArrayBuffer, &boolean);
130    return boolean;
131}
132```
133
134JS code:
135
136```ts
137import hilog from "@ohos.hilog"
138// Import the native APIs.
139import napitest from "libentry.so"
140let script: string = `isArrayBuffer(new ArrayBuffer(8))`
141try {
142  let result = napitest.runJsVm(script);
143  hilog.info(0x0000, 'JSVM', 'IsArrayBuffer: %{public}s', result);
144} catch (error) {
145  hilog.error(0x0000, 'JSVM', 'IsArrayBuffer: %{public}s', error.message);
146}
147```
148
149### OH_JSVM_DetachArraybuffer
150
151Use **OH_JSVM_DetachArraybuffer** to invoke the **Detach()** operation of an **ArrayBuffer** object.
152
153### OH_JSVM_IsDetachedArraybuffer
154
155Use **OH_JSVM_IsDetachedArraybuffer** to check whether an **ArrayBuffer** object has been detached.
156
157CPP code:
158
159```cpp
160// hello.cpp
161#include "napi/native_api.h"
162#include "ark_runtime/jsvm.h"
163#include <hilog/log.h>
164// Register the DetachArraybuffer and IsDetachedArraybuffer callbacks.
165static JSVM_CallbackStruct param[] = {
166    {.data = nullptr, .callback = DetachArraybuffer},
167    {.data = nullptr, .callback = IsDetachedArraybuffer},
168};
169static JSVM_CallbackStruct *method = param;
170// Set property descriptors named DetachArraybuffer and IsDetachedArraybuffer, and associate them with a callback each. This allows the DetachArraybuffer and IsDetachedArraybuffer callbacks to be called from JS.
171static JSVM_PropertyDescriptor descriptor[] = {
172    {"detachArraybuffer", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
173    {"isDetachedArraybuffer", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
174};
175// Define OH_JSVM_DetachArraybuffer and OH_JSVM_IsDetachedArraybuffer.
176static JSVM_Value DetachArraybuffer(JSVM_Env env, JSVM_CallbackInfo info)
177{
178    size_t argc = 1;
179    JSVM_Value args[1] = {nullptr};
180    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
181    JSVM_Value arraybuffer = args[0];
182    JSVM_Status status = OH_JSVM_DetachArraybuffer(env, arraybuffer);
183    if (status != JSVM_OK) {
184        OH_LOG_ERROR(LOG_APP, "JSVM DetachArraybuffer: failed");
185    } else {
186        OH_LOG_INFO(LOG_APP, "JSVM DetachArraybuffer: success");
187    }
188    return arraybuffer;
189}
190
191static JSVM_Value IsDetachedArraybuffer(JSVM_Env env, JSVM_CallbackInfo info)
192{
193    size_t argc = 1;
194    JSVM_Value args[1] = {nullptr};
195    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
196    JSVM_Value arraybuffer = args[0];
197    OH_JSVM_DetachArraybuffer(env, arraybuffer);
198    bool result = false;
199    JSVM_Status status = OH_JSVM_IsDetachedArraybuffer(env, arraybuffer, &result);
200    if (status != JSVM_OK) {
201        OH_LOG_ERROR(LOG_APP, "JSVM IsDetachedArraybuffer: failed");
202    } else {
203        OH_LOG_INFO(LOG_APP, "JSVM IsDetachedArraybuffer: success");
204        OH_LOG_INFO(LOG_APP, "JSVM IsArrayBuffer: %{public}d", result);
205    }
206    JSVM_Value isDetached = nullptr;
207    OH_JSVM_GetBoolean(env, result, &isDetached);
208    return isDetached;
209}
210```
211
212JS code:
213
214```ts
215import hilog from "@ohos.hilog"
216// Import the native APIs.
217import napitest from "libentry.so"
218let script: string = `
219          let arrayBuffer = new ArrayBuffer(10);
220          detachArraybuffer(arrayBuffer);
221          isDetachedArraybuffer(arrayBuffer);
222        `;
223try {
224  let result = napitest.runJsVm(script);
225  hilog.info(0x0000, 'JSVM', 'IsDetachArraybuffer: %{public}s', result);
226} catch (error) {
227  hilog.error(0x0000, 'JSVM', 'IsDetachArraybuffer: %{public}s', error.message);
228}
229```
230
231### OH_JSVM_CreateArraybuffer
232
233Use **OH_JSVM_CreateArraybuffer** to create an **ArrayBuffer** object of the specified size.
234
235CPP code:
236
237```cpp
238// hello.cpp
239#include "napi/native_api.h"
240#include "ark_runtime/jsvm.h"
241#include <hilog/log.h>
242// Register the CreateArraybuffer callback.
243static JSVM_CallbackStruct param[] = {
244    {.data = nullptr, .callback = CreateArraybuffer},
245};
246static JSVM_CallbackStruct *method = param;
247// Set a property descriptor named createArraybuffer and associate it with a callback. This allows the CreateArraybuffer callback to be called from JS.
248static JSVM_PropertyDescriptor descriptor[] = {
249    {"createArraybuffer", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
250};
251// Define OH_JSVM_CreateArraybuffer.
252static JSVM_Value CreateArraybuffer(JSVM_Env env, JSVM_CallbackInfo info)
253{
254    size_t argc = 1;
255    JSVM_Value argv[1] = {nullptr};
256    JSVM_Value result = nullptr;
257    // Parse the input parameters.
258    OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr);
259    int32_t value;
260    size_t length;
261    OH_JSVM_GetValueInt32(env, argv[0], &value);
262    length = size_t(value);
263    void *data;
264    // Create an ArrayBuffer object.
265    JSVM_Status status = OH_JSVM_CreateArraybuffer(env, length, &data, &result);
266    if (status != JSVM_OK) {
267        OH_LOG_ERROR(LOG_APP, "JSVM CreateArraybuffer: failed");
268    } else {
269        OH_LOG_INFO(LOG_APP, "JSVM CreateArraybuffer: success");
270        OH_LOG_INFO(LOG_APP, "JSVM ArrayBuffer length: %{public}d", length);
271    }
272    // Return the created ArrayBuffer.
273    return result;
274}
275```
276
277JS code:
278
279```ts
280import hilog from "@ohos.hilog"
281// Import the native APIs.
282import napitest from "libentry.so"
283let script: string = `createArraybuffer(8)`;
284try {
285  let result = napitest.runJsVm(script);
286  hilog.info(0x0000, 'testJSVM', 'createArraybuffer: %{public}s', result);
287} catch (error) {
288  hilog.error(0x0000, 'testJSVM', 'createArraybuffer: %{public}s', error.message);
289}
290```
291