Last active
August 29, 2015 13:56
-
-
Save alan-andrade/8927850 to your computer and use it in GitHub Desktop.
integrate Rust with C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The C method signature is as follows: | |
int | |
getgrouplist(const char *name, int basegid, int *groups, int *ngroups); | |
// My Rust extern block | |
extern { | |
fn getgrouplist(name: *libc::c_char, | |
basegid: libc::c_int, | |
groups: *libc::gid_t, | |
ngroups: *libc::c_int) -> libc::c_int; | |
} | |
// Trying to use it | |
fn group(pw: *c_passwd, nflag: bool) { | |
let NGROUPS_MAX:uint = unsafe { | |
libc::sysconf(libc::_SC_NGROUPS_MAX) as uint | |
}; | |
let GETGROUPS_T:uint = mem::size_of::<libc::gid_t>(); | |
let mut groups = std::vec::with_capacity(NGROUPS_MAX * GETGROUPS_T); | |
unsafe { groups.set_len(NGROUPS_MAX) }; | |
let mut ngroups = 0; | |
unsafe { | |
getgrouplist((*pw).pw_name, (*pw).pw_gid, groups.as_ptr(), ngroups); | |
} | |
println!("{:d}", unsafe { ngroups }); | |
if ngroups > 0 { | |
print!(" groups="); | |
for i in range(0, ngroups) { | |
if i > 0 { | |
print!(",") | |
} | |
print!("{:d}", groups[i]); | |
let group = unsafe { getgrgid(groups[i] as u32) }; | |
if ptr::is_not_null(group) { | |
let name = unsafe { | |
raw::from_c_str(ptr::read_ptr(group).gr_name) | |
}; | |
print!("({:s})", name); | |
} | |
} | |
println!(""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment