Effortlessly handle C ++ classes and functions from Node.js using SWIG

Sometimes you want to work with C ++ functions and classes from Node.js. For example, when you want to write a GUI of code written in C ++ in Electron or Nw.js.

In general, it seems that Node-ffi is used when calling C ++ code from Node. However, when I read the Tutorial, it's a hassle to write something.

SWIG is known as a binding creation tool that calls C / C ++ functions from Python or Ruby. In fact, if you use this SWIG, you can easily write a Javascript wrapper.

Installation

The stable version of SWIG is 3.0.12, but this is not compatible with Node 7 or later. Use the development version of Github. Note that Node-gyp is required to build the library, so if you don't have it, install it from npm.

wget https://github.com/swig/swig/archive/master.zip
unzip master.zip
cd swig-master
./autogen.sh
./configure
make
sudo make install

Write a trumpet

To practice, read the following code from Node.

complex.hpp:

#include <string>

struct complex
{
    complex(double r=0,double i=0);
    double re;
    double im;
    double abs()const;
    std::string to_str()const;
};

complex.cpp:

#include <cmath>
#include "complex.hpp"

complex::complex(double r,double i): re(r), im(i) {}
double complex::abs()const{ return std::sqrt(re*re+im*im); }
std::string complex::to_str()const{ return std::to_string(re)+"+"+std::to_string(im)+"i"; }

For example, it would be nice if this code could be called from the JS below.

complex.js:

const Complex=require('./complex.node').complex;

let z=new Complex();

console.log (z.abs ()); // I want you to display 0 z.re=3; z.im=4; console.log (z.abs ()); // I want you to display 5 Expect a display like console.log (z.to_str ()); // 3 + 4i

With SWIG, you only have to write this many trumpets.

complex.i:

% module complex // Define a module that can be seen from the outside %{ #include "complex.hpp" // Functions in this can be seen from the outside %}

% include "std_string.i" // Wrap std :: string into a JS string just like writing this %include "complex.hpp"

After that, just write binding.gyp for build, execute SWIG and build.

binding.gyp:

{ "targets": [ { 
    "target_name": "complex",
    "sources": [ "complex.cpp", "complex_wrap.cxx" ]
} ] }

Execute.

swig -javascript -node -c++ complex.i
node-gyp configure build

If you move the created complex.node to a suitable place and execute node complex.js ...

0
5
3.000000+4.000000i

Easy!

Recommended Posts

Effortlessly handle C ++ classes and functions from Node.js using SWIG
Link Java and C ++ code with SWIG
Write code using Ruby classes and instances