Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. use std::ffi::c_void;
  2.  
  3. mod sys {
  4. use super::*;
  5.  
  6. pub type ScopedFunc = unsafe extern "C" fn(*mut c_void);
  7.  
  8. pub unsafe fn scoped(callback: Option<ScopedFunc>, user_data: *mut c_void) {
  9. println!("Doing something fancy in C++");
  10.  
  11. (callback.unwrap())(user_data);
  12.  
  13. println!("Done executing callback.");
  14. }
  15. }
  16.  
  17. struct Scope;
  18.  
  19. impl Scope {
  20. pub fn scoped<F>(mut func: F)
  21. where
  22. F: FnMut(&Scope),
  23. {
  24. unsafe {
  25. sys::scoped(
  26. Some(sure::<F>),
  27. &mut func as *mut _ as *mut std::ffi::c_void,
  28. );
  29. }
  30. }
  31. }
  32.  
  33. unsafe extern "C" fn sure<T>(foo: *mut std::ffi::c_void)
  34. where
  35. T: FnMut(&Scope),
  36. {
  37. let foo = foo as *mut T;
  38. (*foo)(&Scope);
  39. }
  40.  
  41. fn main() {
  42. Scope::scoped(|_| {
  43. println!("hello from callback");
  44. })
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement