我有一个 rubygem,带有用 rust 编写的 native 扩展。
native 扩展支持将其数据结构序列化为 JSON。
但是,虽然我已确认它正在生成 JSON,但在 ruby 端,该字符串始终为空。
这是 ruby 代码:
module RustCuckooFilter
extend FFI::Library
ffi_lib 'libcuckoofilter_cabi'
class Instance < FFI::AutoPointer
def export(path)
RustCuckooFilter.export(self)
end
end
attach_function :export, :rcf_cuckoofilter_export, [Instance], :pointer
和 rust 代码
/// Exports the filter to a file
#[no_mangle]
pub extern "C" fn rcf_cuckoofilter_export(filter: *mut rcf_cuckoofilter) -> *const c_char {
let filter = unsafe { filter.as_mut() };
let serialized = serde_json::to_string(&filter.expect("Given rcf_cuckoofilter* is a null pointer").export()).unwrap();
let cstr = CString::new(serialized).expect("JSON was not a valid c string");
let ptr = cstr.as_ptr();
unsafe {
println!("{:#?}", ptr);
println!("{}", CStr::from_ptr(ptr).to_str().expect("validity"));
}
ptr
}
在 Rust 方面,println!
使用确认指针包含 JSON 字符串。
通过比较它打印的地址和 ruby 中 #export
的返回值,我可以看到使用了相同的指针。
但是,对指针调用 get_bytes(0, 10)
会发现它以空字节开头,并尝试将其转换为字符串会返回空字符串。
我怀疑它被清零了,因为变量的生命周期结束了,我正在 Debug模式下构建;但是,我不清楚我需要更改什么。
最佳答案
想通了 - 我需要在使用rust 的一面使用 CString::into_raw
以防止它被清理。
关于ruby - 通过 FFI 从 rust 到 ruby ,弦变空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173958/