我试图使用节点-ffi库来调用cpp代码。
CPP码
typedef struct{
char * key,
char * value
} ContextAttribute;
typedef struct{
ContextAttribute * attribute,
int count
} Context;这个用在
Status Init(
Handle* handle,
const char* id,
const char* token,
const char* apiKey,
const char* productname,
const char* productVersion,
const char* productLanguage,
PlatformType platform,
const char* userGuid,
EventCb eventcb,
Context * context
);我通过以下节点-ffi javascript代码消费上述cpp代码
var ref = require('ref');
var ffi = require('ffi');
var Struct = require('ref-struct');
var ContextAttribute = new Struct({
key: "string",
value: "string"
});
var Context = new Struct({
attribute: ref.refType(ContextAttribute),
count: "int"
});
'Init': [Status, [
ref.refType(voidPtr),
'string',
'string',
'string',
'string',
'string',
'string',
PlatformType,
'string',
EventCb,
ref.refType(Context)
]],函数的调用方式如下
this.Init(clientId, token, apiKey, productName, productVersion, productLanguage, platform, userGuid, Event, wrapAsNative(callback), Context)我试着用
var context = [{
attribute: [{
key: 'os',
value: 'win'
}],
count: 0
}];
var result = Lib.Init("myClient", testToken, '4d84247c36bd4f63977853eb1e0cb5b7', "asfasd",'12','en_US', 'MAC', 'abcd+1@pqr.com', 'SIGNIN', function(Handle, Event){
}, context);我得到了以下错误:
TypeError:错误设置参数10 - writePointer:缓冲区实例,预期作为TypeError (原生)的第三个参数,at Object.writePointer,Object.set,at Object.set,at Object.alloc (/Users/.../node_modules/ffi/lib/ref.js:516:13)在Object.proxy 作为Init at Object.Lib.Init (/User/./src/Lib.js:130:26)
发布于 2018-05-08 06:03:58
var context = [{
attribute: [{
key: 'os',
value: 'win'
}],
count: 0
}];这不是用Buffer布局创建有效的Context对象的方法。您必须使用var context = new Context;来创建一个正确类型的对象。
这正是错误消息告诉您的-- context不是有效的Buffer。
不确定,但我认为ref也不支持C风格的数组,因此指针+计数结构不会那样工作。如果要使用它们,则必须在C端这样做,并将数组视为不透明的指针类型。
(其实不是真的,这是有可能的。但是它需要修改原始get实例的set和Buffer方法上的偏移量参数。)
不过,链接列表确实有效。
https://stackoverflow.com/questions/49935469
复制相似问题