For our image segmentation algorithm that I had written in C++, I needed to help the full-stack developer wrap the shared library for Node.js. As far as I can see, from a day of googling around and hacking into Node.js, which is a somewhat unfamiliar world for me, that there are two major options:
- using
node-ffi
, or,
addons
as you have already stated.
For 1. above, you do not need to do much. You simply need to require the ffi
, ref
and ref-array
packages/addons in node.js
to be able to call the C API of your application code. There is some nice tutorial that I followed, which helped me get going in 15 minutes.
However, I needed to choose 2. above for our project in the end. This was due to the fact that our full-stack developer was relying on some other addons that needed the latest version of Node.js. Apparently, when we check the issue board of node-ffi
, as of this answer's posting time, it does not support the v9.x family of node.js. Hence, I went the native addons way. It has taken me roughly 4 hours to understand and write the code. I am not sure if it is the most convenient/efficient way possible, but what I did was to
- use buffers to allocate memory in Node.js,
- write a simple addon using
nan
in Node.js that reinterpret_cast
s the char*
buffer of Node.js and calls the very same C API of our shared library, and finally,
- link against the shared library we had created using
binding.gyp
.
Apparently, Native Abstractions for Node.js (aka nan
) is supposed to be used by users to avoid the need to handle breaking changes introduced in v8
. There is another nice tutorial I have found, which helped me solve my problem easily.
Finally, Scott Frees' blog site seems to have a lot of self-contained articles/examples for those who would like to go deeper. He also argues in which situations you should be preferring one approach over the other (node-ffi
over native addons, for instance). Basically, what I understand is that writing native addons will be more efficient, even though for our application it did not matter much. node-ffi
gives satisfactory behaviour, too, as we were solving an image segmentation problem (which anyways takes more time than the call overhead).
So, in short,
I came across the addons but it seems to me, that in order to use it I'll have to convert a lot of code to bring it to that format.
Well, not necessarily! It depends on what you are willing to achieve. It can be as easy as compiling your C++ code for a specific C-API shared library, and then writing a 20-liner wrapper in nan
, which basically does some reinterpret_cast
for in-place memory operations, and finally linking against the library in binding.gyp
.
Is there an easier way?
Yes, there is. node-ffi
can help you solve the problem under half an hour. But then, it might not be the most efficient for your scenario, or it might not be a viable option for you, as it currently does not build with the v9.x family of Node.js.