rust - 在 rust 中将 Vec<&str> 转换为 Vec<&CStr>
问题描述
看看这个函数:
fn exec(cli: Vec<&str>) {
eprintln!("execing: {:?}", cli);
let args: Vec<&CStr> = cli.iter()
.map(|s| CString::new(s.as_bytes()).unwrap().as_c_str())
.collect();
execv(args[0], &args);
debug(args);
}
它接受 aVec<&str>
并将其作为命令执行。我无法将其转换为Vec<&CStr>
(这是execv
需要的)。编译器针对以下操作报告此错误map
:
error[E0515]: cannot return value referencing temporary value
--> src/idea.rs:141:18
|
141 | .map(|s| CString::new(s.as_bytes()).unwrap().as_c_str())
| -----------------------------------^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
如何修复此错误?
解决方案
您必须将所有 CString 收集到一个单独的向量中,以便您的引用在 execv 调用期间有效:
use std::ffi::CString;
use std::ffi::CStr;
fn main() {
let cli = vec!["hello", "world"];
let vec: Vec<_> = cli.iter()
.map(|s| CString::new(s.as_bytes()).unwrap())
.collect();
let vec_obj: Vec<&CStr> = vec.iter().map(|c| c.as_c_str()).collect();
println!("CString:{:?}", vec);
println!("&CStr:{:?}", vec_obj);
}
推荐阅读
- linux - Ubuntu 18.04 上 Docker 的 Elasticsearch 文件描述符错误
- sql - 多值参数在 SSRS 报告中不起作用
- javascript - 来自动态输入文本JS的总和
- html - 内容安全策略问题
- php - 使用 PHP stream_context_create 读取远程二进制文件
- php - 无法调用作曲家命令
- java - ArrayLists and Vector comparison
- python - Why is my requests.Session() starting a new HTTP connection when used within a multiprocessing.Process?
- raku - 访问不同发行版的资源
- python - How to get list of modified files of a Git repo in python?