字符串变为空,通过FFI从生锈到红宝石

问题描述 投票:1回答:1

我有一个带有原生扩展名的rubygem。

本机扩展支持将其数据结构序列化为JSON。

然而,虽然我已经确认它正在生成JSON,但是红宝石端的字符串总是空的。

这是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

和锈代码

/// 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)会显示它以空字节开头,并尝试将其转换为字符串返回空字符串。

我怀疑它已被归零,因为变量的生命周期结束了,我正在调试模式下构建;但是,我不清楚我需要改变什么。

ruby rust ffi
1个回答
2
投票

想出来 - 我需要在锈面上使用CString::into_raw以防止它被清理干净。

© www.soinside.com 2019 - 2024. All rights reserved.