15

我正在尝试使用node-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
);

我正在通过以下node-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:缓冲区实例应为 Object.writePointer (/Users/..../node_modules/ref/lib/ref.js:742:11) 的 TypeError (native) 的第三个参数。在 Object.alloc (/Users/.../node_modules/ffi/lib/ref.js:516:13) 处设置 (/Users/.../node_modules/ffi/ref/lib/ref.js:484:13) ) 在 Object.lib.Init (/Users/.../src/Lib.js) 的 Object.proxy [as Init] (/Users/.../node_modules/ffi/lib/_foreign_function.js:50:22) :130:26)

4

1 回答 1

1
var context = [{
    attribute: [{
         key: 'os',
         value: 'win'
    }],
    count: 0
}];

这不是您使用布局创建有效Buffer对象的方式。Context您必须使用var context = new Context;来创建正确类型的对象。

这正是错误消息告诉您的内容 -context不是有效的Buffer.

不确定,但我认为也不ref支持 C 风格的数组,所以指针 + 计数结构不能那样工作。如果要使用它们,则必须在 C 端执行此操作,并将数组视为不透明指针类型。

(实际上并非如此,这是可能的。但它需要摆弄原始实例的get和方法上的偏移参数。)setBuffer

链接列表确实有效。

于 2018-05-08T06:03:58.593 回答