Hi,
I'm working on a small project which needs to interact with Linux syscalls. Most of these syscalls need structures as input.
If we take the classical C approach with uname
we would write:
struct utsname buf;
uname(&buf);
printf("sysname: %s\n", buf.sysname);
In rust, this is what I came up with:
extern crate libc;
use libc::utsname;
use std::ffi::CString;
extern {
pub fn uname(buf: *mut utsname) -> i32;
}
fn make_utsname() -> utsname {
utsname {
sysname: [0; 65],
nodename: [0; 65],
release: [0; 65],
version: [0; 65],
machine: [0; 65],
domainname: [0; 65],
}
}
fn main() {
let mut buf: utsname = make_utsname();
unsafe { uname(&mut buf); }
let sysname = unsafe { CString::from_raw(buf.sysname.as_mut_ptr()) };
println!("sysname: {}", sysname.to_str().unwrap());
}
While this works and gives the same result, I find having to build a 0-initialized struct a bit tedious. Am I missing something to more quickly get such as struct initialized? I looked into the default trait but cannot implement it for types defined in crates.
Any other pointers / critique of the above code would be warmly welcomed.
Thanks a lot!