Skip to content

Instantly share code, notes, and snippets.

@gabrielschulhof
Last active December 21, 2018 01:01
Show Gist options
  • Save gabrielschulhof/108166bc6e71a755caac6897be5b1f66 to your computer and use it in GitHub Desktop.
Save gabrielschulhof/108166bc6e71a755caac6897be5b1f66 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdio.h>
#include <node_api.h>
static napi_value AcceptTypedArray(napi_env env, napi_callback_info info) {
napi_value typed_array = nullptr;
size_t argc = 1;
assert(napi_get_cb_info(env,
info,
&argc,
&typed_array,
nullptr,
nullptr) == napi_ok);
bool is_typedarray = false;
assert(napi_is_typedarray(env, typed_array, &is_typedarray) == napi_ok);
assert(is_typedarray);
napi_value arraybuffer = nullptr;
napi_typedarray_type typed_array_type;
size_t length = 0;
void* data;
assert(napi_get_typedarray_info(env,
typed_array,
&typed_array_type,
&length,
&data,
&arraybuffer,
nullptr) == napi_ok);
fprintf(stderr,
"type: %d\nlength: %lu\ndata: %p\n",
typed_array_type,
length,
data);
bool is_arraybuffer;
assert(napi_is_arraybuffer(env, arraybuffer, &is_arraybuffer) == napi_ok);
fprintf(stderr,
"backing store is arraybuffer: %s\n", is_arraybuffer ? "true" : "false");
fprintf(stderr, "value: %lf\n", *((double*)(data)));
*((double*)(data)) *= 2;
return nullptr;
}
NAPI_MODULE_INIT() {
napi_value result;
assert(napi_create_function(env,
"acceptTypedArray",
NAPI_AUTO_LENGTH,
AcceptTypedArray,
nullptr,
&result) == napi_ok);
return result;
}
const acceptTypedArray = require('./build/Release/binding')
const buffer = new ArrayBuffer(8);
const array = new Float64Array(buffer);
array[0] = Math.PI;
acceptTypedArray(array);
console.log(array[0]);
const sharedBuffer = new SharedArrayBuffer(8);
const sharedArray = new Float64Array(sharedBuffer);
array[0] = Math.PI;
acceptTypedArray(sharedArray);
console.log(sharedArray[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment