3

Let's say i have source and header files for C code (bus-driver.c and bus-driver.h) can i call functions inside them from node.js

for example bus-driver.h

void bus_init(void);
void bus_write(char *buf);

I want to call these functions from node.js.

Nasr
  • 2,482
  • 4
  • 26
  • 31
  • Maybe a duplicated? http://stackoverflow.com/questions/9629677/how-can-i-use-a-c-library-from-node-js – dfranca Aug 25 '15 at 12:02
  • Or look at: https://nodejs.org/api/addons.html – dfranca Aug 25 '15 at 12:03
  • I read them, but i don't understand them. if you could give me example with bus-driver.h it could be very helpful, thanks anyway. – Nasr Aug 25 '15 at 12:09

1 Answers1

3

The nodeffi seems to be simplest way to do that. I didn't test it so it can has problems that I don't realize now.

But I would suggest to do something like that, following the tutorial. Install nodeffi:

Generate a library for your bus-driver if you don't have one, let's call it libbusdriver.

Then in your javascript do something similar to this:

var ffi = require('ffi');

var libbusdriver = ffi.Library('libbusdriver', {
  'bus_init': [ 'void', [ 'void' ] ],
  'bus_write': [ 'void', [ 'string' ] ],
});
libbusdriver.bus_init();
libbusdriver.bus_write("Hello");

Let me know if it helps.

dfranca
  • 5,156
  • 2
  • 32
  • 60
  • I tried it, and have this error after executing node.js program **Error: Dynamic Linking Error: libusbdriver.so: cannot open shared object file: No such file or directory** the library and test.js file is in the same directory, i tried to rename library .so and .a with no difference – Nasr Aug 25 '15 at 12:52
  • Are you naming it libusbdriver or libbusdriver? – dfranca Aug 25 '15 at 12:57
  • sorry i change it to libbusdriver but get the same error. is it true to place node.js program and the library in the same directory? – Nasr Aug 25 '15 at 13:05
  • Did you generate the library with shared flag on? – dfranca Aug 25 '15 at 13:09
  • I used **gcc -c libbusdriver.c -o libbusdriver.o** to compile and **ar rcs libbusdriver libbusdriver.o** to generate the library – Nasr Aug 25 '15 at 13:17
  • Try using gcc -shared: gcc -shared -o libbusdriver.so libbusdriver.o – dfranca Aug 25 '15 at 13:21
  • i get this error when creating the library **/usr/bin/ld: libbusdriver.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC libbusdriver.o: error adding symbols: Bad value** – Nasr Aug 25 '15 at 13:25
  • Follow the instructions and recompile with -fPIC before generate the shared library – dfranca Aug 25 '15 at 13:31
  • I found the error, ` var libbusdriver = ffi.Library('./libbusdriver', { ...` we should spicify the directory so i added ./ and it worked. very thanks to you. – Nasr Aug 25 '15 at 13:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87894/discussion-between-danielfranca-and-nasr). – dfranca Aug 25 '15 at 13:47