试图在回调之后获取数据,它们没有,是否还希望将数据转换为您需要的结构?
C代码:
main.c
Ibox_Controller_SetSendReaderRequestAction(&sendReaderRequest);
Ibox_Result_ReaderInfo *readerInfoResult = Ibox_Controller_ReaderInfo();
hw.h
Ibox_Result_ReaderInfo *Ibox_Controller_ReaderInfo();
void Ibox_Controller_SetSendReaderRequestAction(IboxSendReaderRequestAction action);
Ibox_MemoryStruct *sendReaderRequest(char *request, int length);
typedef struct {
const char *errorMessage;
const char *bootloaderVersion;
const char *firmwareVersion;
const char *hardwareVersion;
int errorCode;
} Ibox_Result_ReaderInfo;
hw.c
char *sendData(char *buf, int size, uint16_t *retsize)
{
char *retbuf = 0;
....
return retbuf;
}
Ibox_MemoryStruct *sendReaderRequest(char *request, int length)
{
uint16_t responseLength = 0;
char *responseData = sendData(request, length, &responseLength);
Ibox_MemoryStruct *response = malloc(sizeof(Ibox_MemoryStruct));
response->length = responseLength;
response->data = responseData;
return response;
}
首先,我们注册一个处理程序Ibox_Controller_SetSendReaderRequestActio
,其他函数将使用该处理程序,但是问题是在回调之后我无法获得结果。
JS代码
var ffi = require('ffi');
var ref = require('ref');
var ArrayType = require('ref-array');
var StructType = require('ref-struct');
var lib = './libpay/libSDK.so';
var charPtrArray = ArrayType('char *', 64);
var charPtrArrayPtr = ref.refType(charPtrArray);
var voidPtr = ref.refType(ref.types.void);
var Ibox_Result_ReaderInfo = StructType({
errorMessage : string,
bootloaderVersion : string,
firmwareVersion : string,
hardwareVersion : string,
errorCode : string
});
var Ibox_MemoryStruct = StructType({
data : 'string',
length : ref.types.int
});
var sendReaderRequest = ffi.Callback('void', [charPtrArrayPtr, 'int'],
function(request, size) {
console.log(request, size);
return 'action\n1'; //result
});
var ib = ffi.Library(lib, {
"Ibox_Controller_SetSendReaderRequestAction" : ['void', ['pointer']],
"Ibox_Controller_ReaderInfo" : ['void', []],
});
ib.Ibox_Controller_SetSendReaderRequestAction(sendReaderRequest);
var resReaderInfo = ib.Ibox_Controller_ReaderInfo(); //result null why?
答案 0 :(得分:0)
检查您的ffi定义中的Ibox_Controller_ReaderInfo。 我认为
"Ibox_Controller_ReaderInfo" : ['void', []]
应该更像:
"Ibox_Controller_ReaderInfo" : ['void*', []]
甚至
"Ibox_Controller_ReaderInfo" : ['pointer', []]
因为您正在从Ibox_Controller_ReaderInfo()
返回指针,所以
编辑: 再考虑一下,您可能需要遵循以下原则:
const Ibox_Result_ReaderInfo_Ptr = ref.refType(Ibox_Result_ReaderInfo);
var ib = ffi.Library(lib, {
"Ibox_Controller_SetSendReaderRequestAction" : ['void', ['pointer']],
"Ibox_Controller_ReaderInfo" : [Ibox_Result_ReaderInfo_Ptr, []],
});
因为您需要告诉ffi函数返回一个指针。