Skip to content

Instantly share code, notes, and snippets.

@ericho
Created May 2, 2017 04:33
Show Gist options
  • Save ericho/4cd0feec8aa2d3440264cef8d7253b49 to your computer and use it in GitHub Desktop.
Save ericho/4cd0feec8aa2d3440264cef8d7253b49 to your computer and use it in GitHub Desktop.
Rust example
extern crate libc;
use std::ffi::CStr;
#[no_mangle]
pub extern fn testing(argc: i64, argv: *const *const libc::c_char) {
let l = unsafe { array_len(argv) };
println!("argc {}", argc);
println!("len {}", l);
let v = unsafe { array_to_vec(argv, l) };
println!("The array {:?}", v);
}
unsafe fn array_len(mut ptr: *const *const libc::c_char) -> usize {
let mut len = 0;
if !ptr.is_null() {
while !(*ptr).is_null() {
len += 1;
ptr = ptr.offset(1);
}
}
len
}
unsafe fn array_to_vec(mut argv: *const *const libc::c_char, l: usize) -> Vec<String> {
if l == 0 || argv.is_null() {
return Vec::new();
}
let mut myvec: Vec<String> = Vec::with_capacity(l);
while !(*argv).is_null() {
myvec.push(pointer_to_string(*argv));
argv = argv.offset(1);
}
myvec
}
unsafe fn pointer_to_string(s: *const libc::c_char) -> String {
CStr::from_ptr(s).to_string_lossy().into_owned()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment