-
Notifications
You must be signed in to change notification settings - Fork 5
/
manual_ffi_binding_demo.rs
84 lines (72 loc) · 2.67 KB
/
manual_ffi_binding_demo.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#[path = "../manual_bindings.rs"]
mod manual_bindings;
use manual_bindings::root::Demo::{
create_new_person, get_person_info, print_helloworld, print_person_info, Location, Person,
Gender_Male,
};
use std::ffi::{CStr, CString};
use crate::manual_bindings::root::Demo::release_person_pointer;
///
fn main() -> () {
println!("[ Manual FFI bindgins call demo ]\n");
// helloworld
unsafe {
print_helloworld();
}
// `Person` related
let wison_first_name = CString::new("Wison").unwrap();
let wison_last_name = CString::new("Ye").unwrap();
let wison_street = CString::new("My street").unwrap();
let wison_city = CString::new("My city").unwrap();
let wison_state = CString::new("My state").unwrap();
let wison_country = CString::new("My country").unwrap();
let wison_location = Location {
street_address: wison_street.as_ptr(),
city: wison_city.as_ptr(),
state: wison_state.as_ptr(),
country: wison_country.as_ptr(),
};
unsafe {
// Get back `Person` raw pointer
let wison: *mut Person = create_new_person(
wison_first_name.as_ptr(),
wison_last_name.as_ptr(),
Gender_Male,
18,
wison_location,
);
let temp_first_name: String = CStr::from_ptr((*wison).first_name)
.to_string_lossy()
.into_owned();
let temp_last_name: String = CStr::from_ptr((*wison).last_name)
.to_string_lossy()
.into_owned();
let temp_street: String = CStr::from_ptr((*wison).location.street_address)
.to_string_lossy()
.into_owned();
let temp_country: String = CStr::from_ptr((*wison).location.country)
.to_string_lossy()
.into_owned();
// Customize print `Person` instance
let wison_info = format!(
"\n>>> Customized print >>>\n[ Wison Info ]:\nFirst name: {}\nLast name: {}\nLocation:\n\tStreet: {}\n\tCountry: {}\n",
temp_first_name, temp_last_name, temp_street, temp_country
);
println!("{}", wison_info);
// `print_person_info` print
println!(">>> 'print_person_info' print >>>");
print_person_info(wison);
// `get_person_info` print
let wison_info_from_c_string: String = CStr::from_ptr(get_person_info(wison))
.to_string_lossy()
.into_owned();
println!(
">>> 'get_person_info' print >>>{}",
wison_info_from_c_string
);
// Remember to free the instance
release_person_pointer(wison);
// Want to try double free? :)
// release_person_pointer(wison);
}
}