Advertisement
Guest User

Untitled

a guest
Jul 10th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.69 KB | None | 0 0
  1. extern crate libc;
  2. use libc::c_char;
  3. use std::ops::Deref;
  4. use std::ffi::CStr;
  5.  
  6. extern "C" {
  7.     fn hello() -> *const c_char;
  8.     fn goodbye(s: *const c_char);
  9. }
  10.  
  11. struct Greeting {
  12.     message: *const c_char,
  13. }
  14.  
  15. impl Drop for Greeting {
  16.     fn drop(&mut self) {
  17.         unsafe {
  18.             goodbye(self.message);
  19.         }
  20.     }
  21. }
  22.  
  23. impl Greeting {
  24.     fn new() -> Greeting {
  25.         Greeting { message: unsafe { hello() } }
  26.     }
  27. }
  28.  
  29. impl Deref for Greeting {
  30.     type Target = str;
  31.  
  32.     fn deref<'a>(&'a self) -> &'a str {
  33.        let c_str = unsafe { CStr::from_ptr(self.message) };
  34.        c_str.to_str().unwrap()
  35.    }
  36. }
  37.  
  38. fn main() {
  39.  let g = Greeting::new();
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement