feat: add calltoc
This commit is contained in:
37
__ffi/calltoc/src/main.rs
Normal file
37
__ffi/calltoc/src/main.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use std::ffi::{c_char, CStr};
|
||||
use std::ops::Deref;
|
||||
|
||||
extern "C" {
|
||||
fn hello() -> *const c_char;
|
||||
fn goodbye(s: *const c_char);
|
||||
}
|
||||
|
||||
struct Greeting {
|
||||
message: *const c_char,
|
||||
}
|
||||
|
||||
impl Drop for Greeting {
|
||||
fn drop(&mut self) {
|
||||
unsafe { goodbye(self.message); }
|
||||
}
|
||||
}
|
||||
|
||||
impl Greeting {
|
||||
fn new() -> Greeting {
|
||||
Greeting { message: unsafe { hello() } }
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Greeting {
|
||||
type Target = str;
|
||||
fn deref<'a>(&'a self) -> &'a str {
|
||||
let c_str = unsafe{ CStr::from_ptr(self.message) };
|
||||
c_str.to_str().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
let greeting = Greeting::new();
|
||||
println!("{}", greeting.deref());
|
||||
}
|
||||
Reference in New Issue
Block a user