Search code examples
javascriptcnode.jsbuffern-api

Forward arraybuffer from C to JS with node-api


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.


Solution

  • 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