title: Using unsigned char buffer with node-ffi
body: <p>I'm having trouble using a buffer with node-ffi to call the following library function:</p>
  
  <pre><code>int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size) { ... }
  </code></pre>
  
  <p><a href="http://www.intra2net.com/en/developer/libftdi/documentation/group__libftdi.html#ga72d87e30015c98bd0be22e7c8c873345" rel="nofollow">http://www.intra2net.com/en/developer/libftdi/documentation/group__libftdi.html#ga72d87e30015c98bd0be22e7c8c873345</a></p>
  
  <p>Which I have seen used by passing a 'unsigned char buf[size]' to as the buf argument..</p>
  
  <p>So with ffi I try this:</p>
  
  <pre><code>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 &lt;&lt; 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
  </code></pre>
  
  <p>But the result I get is:</p>
  
  <pre><code>-22
  usb bulk read failed
  </code></pre>
  
  <p>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..</p>
  
  <p><a href="http://www.intra2net.com/en/developer/libftdi/documentation/ftdi_8c_source.html#l01749" rel="nofollow">http://www.intra2net.com/en/developer/libftdi/documentation/ftdi_8c_source.html#l01749</a></p>