Hi.
This is my first mail to this list, so hello all. I am doing C++
during daytime for a small company in Germany since nearly 4 years now
but I wrestle with that language a bit longer (since the Visual Studio
6.0 days, uh), well, and never really did a lot of C. There are a few
things about Rust I must say I really like. I am poking around with
rustc since a few weeks, having some fun in the late hours after work.
So much for the introduction.
The question: I have a typical C function that takes a pointer to a
struct as argument. Since a Rust record is binary compatible with a C
struct I can do something like this:
type stat = {
st_dev: dev_t, // ID of device containing file
st_ino: ino_t, // inode number
st_mode: mode_t, // protection
st_nlink: nlink_t, // number of hard links
st_uid: uid_t, // user ID of owner
st_gid: gid_t, // group ID of owner
st_rdev: dev_t, // device ID (if special file)
st_size: off_t, // total size, in bytes
st_blksize: blksize_t, // block size for file system I/O
st_blocks: blkcnt_t, // number of blocks allocated
st_atime: time_t, // time of last access
st_mtime: time_t, // time of last modification
st_ctime: time_t // time of last status change
};
#[link_name = "c"]
native mod sys {
// standard C library is already linked with Rust programs
#[nolink]
fn stat(filename: *c_char, buf: *stat) -> c_int;
}
This might compile and link fine on a POSIX system. However, since I
don't have to include any header like <sys/stat.h> with Rust I can do
something like this:
type stat = {
garbage: c_int, // something wrong here
};
fn create_stat() -> stat {
ret {
garbage: 0 as c_int
}
}
#[link_name = "c"]
native mod sys {
#[nolink]
fn stat(filename: *c_char, buf: *stat) -> c_int;
}
fn main() {
let s = "README.txt";
let buf = create_stat();
str::as_c_str(s, {|nbuf|
sys::stat(nbuf, ptr::addr_of(buf))
});
}
Which will compile and run ...and probably segfault very soon.
While declaring a record in a Rust program is very straightforward it
is cumbersome to retype all the information already present in C
header files, if not dangerous when the structures are not as expected
at runtime. Is there any way to actually get the declaration from a C
header in Rust, i.e. by using a #include statement or to get any
compile time error when the types are not as expected? Am I missing
something?
Benjamin
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev