Skip to content

Commit 7124e5f

Browse files
Gabriel "_|Nix|_" Schulhofmhdawson
authored andcommitted
src: example passing an ArrayBuffer to native func
PR-URL: nodejs#93 Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com> Reviewed-By: NickNaso <nicoladelgobbo@gmail.com>
1 parent c802bcf commit 7124e5f

File tree

4 files changed

+78
-0
lines changed

4 files changed

+78
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <stdio.h>
2+
#include <napi.h>
3+
4+
static void ArrayConsumer(const int32_t* array, size_t length) {
5+
for (size_t index = 0; index < length; index++) {
6+
fprintf(stderr, "array[%lu] = %d\n", index, array[index]);
7+
}
8+
}
9+
10+
static Napi::Value AcceptArrayBuffer(const Napi::CallbackInfo& info) {
11+
if (info.Length() != 1) {
12+
Napi::Error::New(info.Env(), "Expected exactly one argument")
13+
.ThrowAsJavaScriptException();
14+
return info.Env().Undefined();
15+
}
16+
if (!info[0].IsArrayBuffer()) {
17+
Napi::Error::New(info.Env(), "Expected an ArrayBuffer")
18+
.ThrowAsJavaScriptException();
19+
return info.Env().Undefined();
20+
}
21+
22+
Napi::ArrayBuffer buf = info[0].As<Napi::ArrayBuffer>();
23+
24+
ArrayConsumer(reinterpret_cast<int32_t*>(buf.Data()),
25+
buf.ByteLength()/sizeof(int32_t));
26+
27+
return info.Env().Undefined();
28+
}
29+
30+
static Napi::Object Init(Napi::Env env, Napi::Object exports) {
31+
exports["AcceptArrayBuffer"] = Napi::Function::New(env, AcceptArrayBuffer);
32+
return exports;
33+
}
34+
35+
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"targets": [
3+
{
4+
"target_name": "array_buffer_to_native",
5+
"cflags!": [ "-fno-exceptions" ],
6+
"cflags_cc!": [ "-fno-exceptions" ],
7+
"sources": [ "array_buffer_to_native.cc" ],
8+
"include_dirs": [
9+
"<!@(node -p \"require('node-addon-api').include\")"
10+
],
11+
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
12+
}
13+
]
14+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const binding = require('bindings')('array_buffer_to_native');
2+
const array = new Int32Array(10);
3+
4+
array[0] = 19;
5+
array[1] = -41;
6+
array[2] = 98;
7+
array[3] = -922;
8+
array[4] = 587;
9+
array[5] = 12;
10+
array[6] = 221;
11+
array[7] = 49;
12+
array[8] = -96;
13+
array[9] = -1;
14+
15+
binding.AcceptArrayBuffer(array.buffer);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "array_buffer_to_native",
3+
"version": "0.0.0",
4+
"description": "Fill Out a Native Array in JavaScript",
5+
"main": "index.js",
6+
"private": true,
7+
"dependencies": {
8+
"bindings": "~1.2.1",
9+
"node-addon-api": "^1.0.0"
10+
},
11+
"scripts": {
12+
"test": "node index.js"
13+
}
14+
}

0 commit comments

Comments
 (0)