v0.23.0
-
Add
napi_create_external_arraybuffer
, theArrayBuffer
memory is copy from wasm, useemnapi_sync_memory
to sync memory between wasm and JavaScript, use runtime method$emnapiSyncMemory
on JavaScript sidevoid finalizer(napi_env env, void* finalize_data, void* finalize_hint) { free(finalize_data); } napi_value createExternalArraybuffer(napi_env env, napi_callback_info info) { uint8_t* external_data = malloc(3); external_data[0] = 0; external_data[1] = 1; external_data[2] = 2; napi_value array_buffer; napi_create_external_arraybuffer(env, external_data, 3, finalizer, NULL, &array_buffer); external_data[0] = 3; // JavaScript ArrayBuffer memory will not change emnapi_sync_memory(env, array_buffer, 0, external_data, NAPI_AUTO_LENGTH, false); // after sync memory, new Uint8Array(array_buffer)[0] === 3 return array_buffer; }
declare function emnapiSyncMemory ( arrayBufferOrView: ArrayBuffer | ArrayBufferView, offset?: number, pointer?: number, len?: number, js_to_wasm?: boolean ): void const array_buffer = Module.emnapiExports.createExternalArraybuffer() new Uint8Array(array_buffer)[1] === 4 Module.emnapiSyncMemory(array_buffer, 0, 0, -1, true)
-
ArrayBuffer related API always return
data
pointer, the memory could be a copy from JavaScript ArrayBuffer, useemnapi_get_memory_address
to check if the memory should be released by user,napi_create_arraybuffer
napi_get_arraybuffer_info
napi_get_typedarray_info
napi_get_dataview_info
void* data; napi_get_typedarray_info(env, typedarray, NULL, NULL, &data, NULL, NULL); void* address; emnapi_ownership ownership; bool runtime_allocated; emnapi_get_memory_address(env, typedarray, &address, &ownership, &runtime_allocated); assert(address == data); if (data != NULL && runtime_allocated && ownership == emnapi_userland) { // user should free data // free(data); }