Using unsigned char buffer with node-ffi

2.6k views Asked by At

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) { ... }

http://www.intra2net.com/en/developer/libftdi/documentation/group__libftdi.html#ga72d87e30015c98bd0be22e7c8c873345

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

1

There are 1 answers

1
3demax On

Seems like it fails because you can't just feed it with void context:

ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
if (ret < 0)
  ftdi_error_return(ret, "usb bulk read failed");

ftdi should be struct http://www.intra2net.com/en/developer/libftdi/documentation/ftdi_8h_source.html#l00219

Try using ref-struct library for this.