Skip to content

Instantly share code, notes, and snippets.

@ryosuzuki
Last active March 3, 2024 21:00
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryosuzuki/186958bf1abb0492f626 to your computer and use it in GitHub Desktop.
Save ryosuzuki/186958bf1abb0492f626 to your computer and use it in GitHub Desktop.
Node-ffi example: Passing and receiving array object between Node.js and C++ binding
var repl = require('repl');
var ffi = require('ffi');
var ref = require('ref');
var ArrayType = require('ref-array');
var int = ref.types.int;
var IntArray = ArrayType(int);
var lib = ffi.Library('mylib', {
'createMatrix': [IntArray, [int, IntArray, int] ]
});
var a = [0, 1, 2, 3, 4];
var array = new IntArray(a);
var result = lib.createMatrix(100, array, array.length);
repl.start('> ').context.r = result;
#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
extern "C" {
int *createMatrix(int n, int arr[], int size) {
sp_mat A = zeros<sp_mat>(n, n);
sp_mat B = zeros<sp_mat>(n, n);
for (int i =0; i<size; ++i) {
A(i, i) = arr[i]+1;
B(i, i) = arr[i];
}
sp_mat C = A*B;
cout << C.t() << endl;
for (int i=0; i< size; ++i) {
arr[i] = C(i, i);
}
return arr;
}
}

Node-ffi with IntArray

Passing and receiving array object between Node.js and C++ binding

$ g++ -dynamiclib -o mylib.dylib main.cpp
$ node index.js
[matrix size: 100x100; n_nonzero: 4; density: 0.04%]

     (1, 1)          2.0000
     (2, 2)          6.0000
     (3, 3)         12.0000
     (4, 4)         20.0000


> r
[ buffer: <Buffer@0x102805568 > ]
> r[0]
0
> r[1]
2
> r[2]
6
> r[3]
12
> r[4]
20
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment