使用Ruby FFI调用Rust库时出现分段错误 [英] Segmentation fault when calling a Rust lib with Ruby FFI
问题描述
我想将String
传递给Rust库,但是它总是会引发分段错误.
I want to pass in a String
to a Rust lib, but it always throws a segmentation fault.
代码如下:
// lib.rs
#[no_mangle]
pub extern fn process(foo: String) -> String {
foo
}
还有Ruby文件:
# embed.rb
require 'ffi'
module Hello
extend FFI::Library
ffi_lib 'target/release/libembed.dylib'
attach_function :process, [ :string ], :string
end
puts Hello.process("foo")
推荐答案
免责声明:我以前从未使用过Ruby-FFI.我将继续在文档中找到我所能找到的东西.
Disclaimer: I've never used Ruby-FFI before; I'm going on what I can find in the documentation.
根据关于类型的Ruby-FFI Wiki页面,:string
是等效的到以NUL终止的C字符串. 这与Rust String
不同. Rust中的String
(当前)大三倍!
According to the Ruby-FFI wiki page on types, :string
is equivalent to a NUL-terminated C string. This is not the same as a Rust String
. A String
in Rust is (presently) three times larger!
Rust中的对应类型为*const ::libc::c_char
.值得注意的是,还设计了 std::ffi::CString
用于创建C字符串,以及 std::ffi::CStr
是安全的可以从 ,CString
或*const c_char
创建的包装器类型.请注意,都不与*const c_char
兼容!
The corresponding type in Rust would be *const ::libc::c_char
. Of note, there is also std::ffi::CString
, which is designed for creating C strings, and std::ffi::CStr
which is the safe wrapper type which can be created from either a CString
or a *const c_char
. Note that neither of these is compatible with *const c_char
!
总而言之,要在Rust中处理C字符串,您将不得不弄乱类型.另外请记住,根据您实际要执行的操作,您可能还需要使用libc::malloc
和libc::free
手动管理内存.
In summary, to deal with C strings in Rust, you're going to have to juggle the types. Also keep in mind that, depending on what you're actually trying to do, you may need to also deal with manually managing memory using libc::malloc
and libc::free
.
对"Rust FFI C字符串处理"的答案给出了有关如何在Rust中处理C字符串的更多详细信息.尽管问题的上下文正在与C代码集成,但在您的情况下,它也应同样有用.
This answer to "Rust FFI C string handling" gives more details on how to deal with C strings in Rust. Although the context for the question is integrating with C code, it should be equally useful in your case.
这篇关于使用Ruby FFI调用Rust库时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!