I'm having trouble using a buffer with node-ffi to call the following library function:
int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size) { ... }
Which I have seen used by passing a 'unsigned char buf[size]' to as the buf argument..
So with ffi I try this:
ffi = require 'ffi'
ref = require 'ref'
ftdiContext = ref.types.void
ftdiContextPtr = ref.refType ftdiContext
ftdi = ffi.Library 'libftdi',
'ftdi_init': [ 'int', [ ftdiContextPtr ] ]
'ftdi_usb_open': [ 'int', [ ftdiContextPtr, 'int', 'int' ] ]
'ftdi_usb_open_desc': [ 'int', [ ftdiContextPtr, 'int', 'int', 'string', 'string'] ]
'ftdi_get_error_string': [ 'string', [ ftdiContextPtr ] ]
'ftdi_set_bitmode': [ 'int', [ ftdiContextPtr, 'uchar', 'uchar' ] ]
'ftdi_set_baudrate': [ 'int', [ ftdiContextPtr, 'int' ] ]
'ftdi_read_data': [ 'int', [ ftdiContextPtr, ref.refType(ref.types.uchar), 'int' ] ]
BITMODE_RESET = 0x00
BITMODE_BITBANG= 0x01
BITMODE_MPSSE = 0x02
BITMODE_SYNCBB = 0x04
BITMODE_MCU = 0x08
BITMODE_OPTO = 0x10
BITMODE_CBUS = 0x20
BITMODE_SYNCFF = 0x40
inputPin = 1
outputPin = 2
rxBaudRate = 9600
txBaudRate = 4500
rxBufSize = 10
buf = new Buffer rxBufSize
ctx = ref.alloc ftdiContextPtr
console.log ftdi.ftdi_init ctx
console.log ftdi.ftdi_usb_open_desc ctx, 0x0403, 0x6001, null, 'FTG4GJL1'
console.log ftdi.ftdi_set_bitmode ctx, inputPin << outputPin , BITMODE_BITBANG
console.log ftdi.ftdi_set_baudrate ctx, rxBaudRate
console.log ftdi.ftdi_read_data ctx, buf, buf.length
console.log ftdi.ftdi_get_error_string ctx
But the result I get is:
-22
usb bulk read failed
The ftdi_read_data C function makes a call to usb_bulk_read (from libusb) which takes 'char *' as it's buffer argument - I'm not sure if this is affecting anything..
http://www.intra2net.com/en/developer/libftdi/documentation/ftdi_8c_source.html#l01749
Seems like it fails because you can't just feed it with void context:
ftdi
should be struct http://www.intra2net.com/en/developer/libftdi/documentation/ftdi_8h_source.html#l00219Try using
ref-struct
library for this.