2

我正在使用 Node-ffi 为MITIE编写节点绑定。但我有问题,

函数的参数是char**:一个以 NULL 结尾的 C 字符串数组,如下所示:

int run (char** tokens)
{
    try
    {
        std::vector<std::string> words;
        for (unsigned long i = 0; tokens[i]; ++i)
            words.push_back(tokens[i]);

        return 1;
    }
    catch(...)
    {
        return 0;
    }
}

这就是我使用 ffi 所做的:

const ffi = require('ffi');
const ArrayType = require('ref-array');

const StringArray = ArrayType('string')

const test = ffi.Library('test', {
  'run': [ 'int', [StringArray] ]
});

test.run(['a', 'b']);

但我得到了:Segmentation fault: 11

我将示例代码上传到了这个 repo

在这个 repo 中你还可以看到我用ctypes写了一个 Python 绑定,它运行良好。

这是我的运行环境:

  • npm@3.10.10
  • 节点@7.10.0
  • 达尔文 x64 17.0.0
  • MacBook Pro(13 英寸,2016 年,四个雷雳 3 端口)
  • macOS 10.13
4

1 回答 1

1

您必须使用 NULL 显式终止令牌数组:

const ffi = require('ffi');
const ArrayType = require('ref-array');
const ref = require('ref');

const StringArray = ArrayType('string')

const test = ffi.Library('test', {
  'run': [ 'int', [StringArray] ]
});

console.log(test.run(['a', 'b', ref.NULL])); // -> 2
于 2017-10-31T12:42:21.023 回答