3

Im currently trying to do some low level coding with JS. For that reason im using https://nodejs.org/api/n-api.html to add custom C code to my node.js runtime.

I get passing values and changing them in c to work, even reading arraybuffers and interpreting them the way i want to in C, but im only able to return limited JS values (numbers and strings, as seen in this part https://nodejs.org/api/n-api.html#n_api_functions_to_convert_from_c_types_to_n_api)

Does anybody know how to get N-API arraybuffers? I'd want give my JS a certain buffer i defined in C, and then work via Dataviews.

2 Answers 2

4

I found the answer: https://nodejs.org/api/n-api.html#n_api_napi_create_external_arraybuffer

I was looking for different keywords than "external", but this is exactly what I looked for: You define a buffer in C beforehand and then create a NAPI/JS array buffer which uses that underlying buffer. napi_create_arraybuffer would clear the buffer, which could then be manipulated in C as well, but you couldn't e.g. load a file and then use that buffer. So napi_create_external_arraybuffer is the way to go.

edit: when I asked the question I was writing my open-source bachelor's thesis, so here's how I used it in the end: https://github.com/ixy-languages/ixy.js/blob/ce1d7130729860245527795e483b249a3d92a0b2/src/module.c#L112

Sign up to request clarification or add additional context in comments.

1 Comment

@GirkovArpa sure! I asked this question to help with my bachelor's thesis, and since its open-source, I can simply show you how I used it: github.com/ixy-languages/ixy.js/blob/…
2

I don‘t know if this helps (I‘m also relatively new to N-API.) but you can create an arraybuffer from a void* and a fixed length: https://nodejs.org/api/n-api.html#n_api_napi_create_arraybuffer

For example:

napi_value CreateArrayBuffer(napi_env env, napi_callback_info info) {
  // the value to return
  napi_value arrayBuffer;

  // allocates 100 bytes for the ArrayBuffer
  void* yourPointer = malloc(100 /* bytes */);

  // creates your ArrayBuffer
  napi_create_arraybuffer(env, 100 /* bytes */, &yourPointer, &arrayBuffer);

  return arrayBuffer; // ArrayBuffer with 100 bytes length
}

1 Comment

close enough, I answered the question in this thread, if you're interested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.