使用带有node-ffi的unsigned char缓冲区

时间:2014-11-14 17:56:24

标签: node.js node-ffi

我在使用带有node-ffi的缓冲区调用以下库函数时遇到了问题:

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

我通过将'unsigned char buf [size]'作为buf参数传递给我使用过。

所以用ffi我试试这个:

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

但我得到的结果是:

-22
usb bulk read failed

ftdi_read_data C函数调用usb_bulk_read(来自libusb),它将'char *'作为缓冲区参数 - 我不确定这是否会影响任何东西..

http://www.intra2net.com/en/developer/libftdi/documentation/ftdi_8c_source.html#l01749

1 个答案:

答案 0 :(得分:0)

似乎它失败了,因为你不能用虚拟上下文来提供它:

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应为struct http://www.intra2net.com/en/developer/libftdi/documentation/ftdi_8h_source.html#l00219

请尝试使用ref-struct library