Skip to content

Instantly share code, notes, and snippets.

@ndenev
Created June 21, 2017 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndenev/3219bc3650b51197014c43f647a23e86 to your computer and use it in GitHub Desktop.
Save ndenev/3219bc3650b51197014c43f647a23e86 to your computer and use it in GitHub Desktop.
rust ffi test
use std::ffi::{CString, CStr};
fn test1() {
let i = String::from("test_string1");
let r = CString::new(i).unwrap().as_bytes_with_nul().as_ptr();
let s = unsafe {
CStr::from_ptr(r as *const i8).to_string_lossy().into_owned()
};
println!("TEST1: {}", s);
}
fn test2() {
let i = String::from("test_string2");
let c = CString::new(i).unwrap();
let r = c.as_bytes_with_nul().as_ptr();
let s = unsafe {
CStr::from_ptr(r as *const i8).to_string_lossy().into_owned()
};
println!("TEST2: {}", s);
}
fn main() {
test1();
test2();
}
nikolay   master  ~  ffi-test  cargo run
Compiling ffi-test v0.1.0 (file:///Users/nikolay/ffi-test)
Finished dev [unoptimized + debuginfo] target(s) in 0.88 secs
Running `target/debug/ffi-test`
TEST1:
TEST2: test_string2
nikolay   master  ~  ffi-test 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment