我正在尝试用 Node FFI 包装一个 Rust 库(它公开一个 C API)。我有以下代码包装了两个函数。一个是返回指针的“构造函数”。另一个接受一个指针并返回 C 字符串。
var libcomm = ffi.Library('lib/c_api/target/debug/libcomm', {
'comm_address_for_content': ['pointer', ['string']],
'comm_address_to_str': ['string', ['pointer']]
});
当我使用响应的异步调用comm_address_to_str
是正确的。但是,当我尝试使用同步样式调用该函数时,它会返回垃圾,或者很少会返回正确的结果。以下 nodeunit 测试练习该场景:
const comm = require("../").libcomm;
exports.testAddressForContent = function (test) {
const ptr = comm.comm_address_for_content('test');
const result = comm.comm_address_to_str(ptr);
test.equal(result, 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'); // always fails
console.log('sync', result); // random garbage
comm.comm_address_to_str.async(ptr, function(err, result) {
test.equal(result, 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'); // always passes
console.log('async', result); // 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'
test.done();
});
}
我不知道是什么原因造成的,但我需要能够使用同步调用样式。我包装的 Rust 库的 C API 在这里。