Node-ffi 绑定到 NULL 终止的 C 字符串数组,但出现“分段错误:11”
Node-ffi Bindings to An array of NULL terminated C strings, but got `Segmentation fault: 11`
我正在使用 Node-ffi 为 MITIE 编写 Node 绑定。但是我遇到了问题,
一个函数的参数是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
。
我把示例代码上传到this repo。
并且在这个 repo 中你还可以看到我已经写了一个 Python 绑定 ctypes,它运行良好。
这是我的运行环境:
- npm@3.10.10
- node@7.10.0
- 达尔文 x64 17.0.0
- MacBook Pro(13 英寸,2016 年,四个 Thunderbolt 3 端口)
- macOS 10.13
您必须使用 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
我正在使用 Node-ffi 为 MITIE 编写 Node 绑定。但是我遇到了问题,
一个函数的参数是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
。
我把示例代码上传到this repo。
并且在这个 repo 中你还可以看到我已经写了一个 Python 绑定 ctypes,它运行良好。
这是我的运行环境:
- npm@3.10.10
- node@7.10.0
- 达尔文 x64 17.0.0
- MacBook Pro(13 英寸,2016 年,四个 Thunderbolt 3 端口)
- macOS 10.13
您必须使用 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