Created
May 2, 2017 04:33
-
-
Save ericho/4cd0feec8aa2d3440264cef8d7253b49 to your computer and use it in GitHub Desktop.
Rust example
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
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