无法将字符串从 Ruby 传递到我的 Rust 函数中

Can't pass a string into my Rust function from Ruby

我正在尝试调用一个接受字符串的函数,用 Rust 编写。

然后将 Rust 代码编译为 C 并通过 FFI gem.

包含在我的 Ruby 代码中

当我调用 Rust 函数并传递一个字符串时,我什么也没得到。

防锈代码:

#[no_mangle]
pub extern fn speak(words: &str) {
  println!("{}", words);
}

Ruby代码:

require 'ffi'

module Human
  extend FFI::Library
  ffi_lib '../target/release/libruby_and.dylib'
  attach_function :speak, [:string], :void
end

Human.speak("Hello, we are passing in an argument to our C function!!")

根据documentation:string表示一个null-terminated字符串,在C中是char *&str参数不等同于type: a &str 是一个复合值,由一个指针和一个长度组成。

最安全的解决方案是更改 Rust 函数以接受 *const c_char。然后,您可以使用 CStr::from_ptr and CStr::to_str 更轻松地使用它。

或者,您可以在 Ruby 代码中定义一个包含指针和长度的结构,并将其传递给 Rust 函数。然而,不能保证这个结构总是匹配切片的内存布局,所以为了 100% 安全,你应该在你的 Rust 代码中定义等效的结构(使用 #[repr(C)]),然后,使用这个结构,调用 slice::from_raw_parts to construct a slice (&c_char or &u8), which you can then turn into a &str with str::from_utf8.