Call C++ library from Node.js (Node addons / node-ffi)

≡放荡痞女 提交于 2019-11-27 21:35:42

node-ffi seems to be primarily for C programs. I went through this in the last week, and found much better luck with node addons. What you have to do is write a shim between the C++ code in the library and node.js. In my case, I needed to encode and decode packets for a security protocol, so I made node buffers that contained the packets, and wrote C++ code that got the data out of the buffers, then send the data to my C code that encoded and decoded packets.

This page: http://luismreis.github.io/node-bindings-guide/docs/returning.html has some great examples of how to get data in and out of node.js buffers in C++.

nbind now makes it easier to write Node.js addons using external C++ libraries. You basically create a new source file including the library headers, the nbind headers and some macro calls listing the library's classes and methods. Then nbind handles the rest.

libui-node is a real-world example using nbind to call libui for generating user interfaces with native widgets from Node.js. There's also a short tutorial how to create bindings for vg, a bioinformatics-related C++ library.

What is missing from the other answer? I am happy to help. The code example there is written in C++. I am illustrating how people (who make libraries in C or C++) define an external interface for others to consume. The point of ffi is that you write your wrapper in whatever language you are using (in this case javascript) rather than C/C++ (as in the case of node extensions.) If your original library is a shared DLL used in other things, it already has an interface, you just need to write wrapper-code in javascript to tell node how it works, rather than write something in C++ and expose it in a native nodejs library.

There is pretty easy way to link any your library(.so .dll .a). You should add library with correct path in binging.gyp file:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ],
      "libraries": [
            "path/toYourLibrary/yourLibName.dll or yourLibName.so"
          ] 
    }
  ]
}

Also there is more simpler way to write good addons using nan. Check link for more information github link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!