我正在尝试编写一个将命令行实用程序(image-magick)的标准输出加载到结构成员中的函数。我认为由于图像可以是MB,所以我最好避免复制。
/// An image data container used internally.
/// Images are 8-bit single channel for now.
pub struct Image<'a> {
/// Width of the image in pixels.
pub width: u32,
/// Height of the image in pixels.
pub height: u32,
/// The buffer containing the image data, as a slice.
pub pixels: &'a [u8],
}
// Load a file by first using imageMagick to convert it to a .pgm file.
fn load_using_magick<'a>(path: Path) -> Image<'a> {
use std::io::Command;
let output:IoResult<ProcessOutput> = Command::new("convert")
.arg("-format pgm")
.arg("-depth 8")
.arg(path)
.arg("-")
.output();
let output_unwrapped:ProcessOutput = match output {
Ok(o) => o,
Err(e) => panic!("Unable to run ImageMagick's convert tool in a separate process! convert returned: {}", e),
};
let bytes: &[u8] = match output_unwrapped.status.success() {
false => panic!("signal or wrong error code from sub-process?"),
true => output_unwrapped.output.as_slice(),
};
// Note, width and height will eventually get parsed out of "bytes"
// and the returned Imaeg.pixels will point to a slice of the (already)
// heap allocated memory. I just need to figure out ownership first...
Image{width:10,height:10,pixels:bytes}
}
当标准库std :: io :: Process :: Command :: output()被调用时,我想保留的一大堆内存是由标准库(或内核?)分配的。 >
使用借阅检查器编译失败:
src/loaders.rs:41:17: 41:40 error: `output_unwrapped.output` does not live long enough src/loaders.rs:41 true => output_unwrapped.output.as_slice(), ^~~~~~~~~~~~~~~~~~~~~~~ src/loaders.rs:21:51: 48:2 note: reference must be valid for the lifetime 'a as defined on the block at 21:50... src/loaders.rs:21 fn load_using_magick<'a>(path: Path) -> Image<'a> { src/loaders.rs:22 use std::io::Command; src/loaders.rs:23 src/loaders.rs:24 let output:IoResult<ProcessOutput> = Command::new("convert") src/loaders.rs:25 .arg("-format pgm") src/loaders.rs:26 .arg("-depth 8") ... src/loaders.rs:21:51: 48:2 note: ...but borrowed value is only valid for the block at 21:50 src/loaders.rs:21 fn load_using_magick<'a>(path: Path) -> Image<'a> { src/loaders.rs:22 use std::io::Command; src/loaders.rs:23 src/loaders.rs:24 let output:IoResult<ProcessOutput> = Command::new("convert") src/loaders.rs:25 .arg("-format pgm") src/loaders.rs:26 .arg("-depth 8")
这对我来说很有意义;我试图保留的所有数据块都超出了范围,在值返回的结构中留下了一个悬空指针。那么,在返回存储区之前,我该如何将其所有权真正转移到结构中呢?
我已经读过Rust Lifetimes Manual。
我正在尝试编写一个将命令行实用程序(image-magick)的标准输出加载到结构成员中的函数。我认为由于图像可以是MB,所以我最好避免...
您的签名声称,无论呼叫者希望的生存时间如何,您都可以返回Image<'that_lifetime>
。实际上,您声称要返回Image<'static>
,其中包含&'static [u8]
,即指向在整个程序执行过程中都有效的字节片的指针。显然,您实际从中获取字节片的ProcessOutput
寿命不长。