ruby - 通过 FFI 从 rust 到 ruby ,弦变空

标签 ruby rust ffi

我有一个 ruby​​gem,带有用 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/

相关文章:

javascript - 自动为 TinyMCE 插入的标题生成 id

rust - 无法移出 `[Foo;2]` 类型,一个非复制数组

namespaces - 是否可以在不污染命名空间的情况下声明 extern "C"函数?

rust - 通过 Rust FFI 更改 C 数组元素

c - 如何在不泄漏内存的情况下将 Rust 结构和方法实现为 C 中的 Vec?

ruby-on-rails - 如何将 SQL 查询转换为 ActiveRecord

ruby-on-rails - 为什么 find_by_sql 不适用于 PostgreSQL?

ruby - 是否可以为 Ruby 创建 Crystal 绑定(bind)?

rust - libgcc和Rust系统库中 `__udivti3'的多个定义

rust - "the trait bound std::fmt::Display is not satisfied"是什么意思?