我试图在Rust中进行一些动态库加载。从动态加载的库函数传递大Vec
时,我遇到了分段错误。它是创建指定大小的Vec<i32>
的基本功能。如果Vec
远大于8MB,程序会在OSX上遇到段错误。我在linux上运行时没遇到同样的问题,任何人都可以看看这个并告诉我,我是否在这里做错了什么?我用以下方式运行:
$ cargo build --release
$ ./target/release/linkfoo
8281
[1] 84253 segmentation fault ./target/release/linkfoo
[package]
name = "linkfoo"
version = "0.1.0"
authors = ["Nate Mara <nathan.mara@kroger.com>"]
[dependencies]
libloading = "0.3.0"
[lib]
name = "foo"
crate-type = ["dylib"]
extern crate libloading as lib;
fn main() {
let dylib = lib::Library::new("./target/release/libfoo.dylib").expect("Failed to load library");
let func = unsafe {
let wrapped_func: lib::Symbol<fn(&[i32]) -> Vec<i32>> = dylib.get(b"alloc")
.expect("Failed to load function");
wrapped_func.into_raw()
};
let args = vec![8182];
println!("{}", func(&args).len());
}
#[no_mangle]
pub fn alloc(args: &[i32]) -> Vec<i32> {
let size = args[0] as usize;
let mut mat = Vec::with_capacity(size);
for _ in 0..size {
mat.push(0);
}
mat
}
答案 0 :(得分:1)
Rust使用系统分配器用于动态库,而jemalloc用于所有其他代码。加载程序的这种差异导致了段错误,我可以通过将其添加到main.rs
的顶部来修复它:
#![feature(alloc_system)]
extern crate alloc_system;