using napi_get_typedarray_info to convert JS typed array to C array

45 Views Asked by At

I have an application which has JS and C layers. From JS layer, I call function to C layer passing the JS typed array. The C function has to convert to C array. I am doing the following. It looks like from doc , I need to create a DataView before accessing the internal buffer(byte array). Will this below method cause issues?

JS:

const float32arr = new Float32Array([32.12,12.2);

C Layer:
getCArr(napi_value value) {
   void *data = NULL;
   napi_typedarray_type type;
   size_t num, bytOffset = 0;
   napi_value arrBuf;
   // get typed array , value information 
   napi_get_typedarray_info(env, value, &type, &num, &data,
                &arrBuf, &byteOffset);


   // copy to C float array
   float *farr = (float *) malloc(num * 4);
   if (type == napi_float32_array) {
     memcpy(farr, data + byteOffset, num * 4);
     
   }

   // print array 
   for (int i = 0; i < num; i++) {
     printf(" Ele %f \n", farr[i]);
   }
}

I tried creating dataview using ArrayBuffer and read elements, but it didn't work

napi_create_dataview(env, byteLength, arrBuf, byteOffset, &dataView)

napi_get_element(env, dataView, 0, val);

napi_typeof(env, val, &valtype);

The valtype is always undefined.

1

There are 1 best solutions below

0
On

It looks like using raw bytes is safe. resolving for now..