Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. use std::{
  2. alloc::{alloc as std_alloc, dealloc as std_dealloc, Layout},
  3. ffi::CStr,
  4. mem,
  5. os::raw::c_char,
  6. };
  7.  
  8. unsafe fn as_str<'a>(it: *mut [c_char]) -> &'a str {
  9. CStr::from_ptr(it as *const _).to_str().unwrap()
  10. }
  11.  
  12. unsafe fn alloc<T>() -> *mut T {
  13. std_alloc(Layout::new::<T>()) as *mut T
  14. }
  15.  
  16. unsafe fn dealloc<T>(it: *mut T) {
  17. std_dealloc(it as *mut _, Layout::new::<T>());
  18. }
  19.  
  20. unsafe fn use_it(it: *mut [c_char; 10]) {
  21. // use it
  22. println!("{}", as_str(it));
  23. println!("{:?}", *it);
  24.  
  25. // we're done with it, so de-allocate it
  26. dealloc(it);
  27. }
  28.  
  29. fn main() {unsafe{
  30. // allocate it
  31. let it: *mut [c_char; 10] = alloc();
  32.  
  33. // initialize it
  34. *it = *mem::transmute::<_, &_>(b"P455w04d\0\0");
  35.  
  36. // use it
  37. use_it(it);
  38.  
  39. // we're done with it, so de-allocate it
  40. dealloc(it);
  41. }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement