gpt4 book ai didi

c - Rust,如何与 gethostname() std::libc 交互

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:47 27 4
gpt4 key购买 nike

我是 Rust 的新手,我正在尝试编写 hostname 实用程序,形成一个 core-utils 的 rust backport。更多信息:https://github.com/uutils/coreutils

我有以下程序:

use std::libc;

extern {
pub fn gethostname(name: *libc::c_char, size: libc::size_t) -> libc::c_int;
}


fn main() {
unsafe {
let len = 34 as uint;
let mut buf = std::vec::with_capacity(len);
std::vec::raw::set_len (&mut buf, len as uint);

gethostname (std::vec::raw::to_ptr(buf), len as u64);
println(format!("{:?}", buf));

println(format!("{:?}", len));
//println(std::str::from_chars(buf));
}
}

我试图打印到 char vector 中的任何 gethostname 副本,但我得到的东西看起来不像字符串。

~[65i8, 108i8, 97i8, 110i8, 115i8, 45i8, 77i8, 97i8, 99i8, 66i8, 111i8, 111i8, 107i8, 45i8, 80i8, 114i8, 111i8, 46i8, 108i8, 111i8, 99i8, 97i8, 108i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8]
34u

我需要做什么才能:1. 确保 gethostname() 正在做我认为正在做的事情?2. 确保我正确编码?

最佳答案

buf 是一个 ~[u8] 并按原样打印(即任意数字的 vector ); std::str::from_utf8_ownedstd::str::from_utf8_slice将(假定的)UTF-8 [u8] 转换为 str。 (后者在 master 中称为 from_utf8;0.8 from_utf8 是坏的,已被删除,它进行分配和复制,而这两者都不做。)

因此,类似于

use std::{libc, str, vec};

extern {
pub fn gethostname(name: *mut libc::c_char, size: libc::size_t) -> libc::c_int;
}


fn main() {
let len = 34u;
let mut buf = std::vec::from_elem(len, 0u8);

let err = unsafe {gethostname (vec::raw::to_mut_ptr(buf) as *mut i8, len as u64)};
if err != 0 { println("oops, gethostname failed"); return; }

// find the first 0 byte (i.e. just after the data that gethostname wrote)
let actual_len = buf.iter().position(|byte| *byte == 0).unwrap_or(len);

// trim the hostname to the actual data written
println(str::from_utf8_slice(buf.slice_to(actual_len)));
}

将打印主机名。

文档:

关于c - Rust,如何与 gethostname() std::libc 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20450637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com