Advertisement
NLinker

Rust FFI

Dec 26th, 2018
501
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.71 KB | None | 0 0
  1.  
  2. extern crate simple_regex;
  3.  
  4. extern crate libc;
  5.  
  6. use std::vec::Vec;
  7. use std::boxed::Box;
  8. use std::ffi::CStr;
  9. use std::str;
  10. use libc::{c_char, size_t, c_void};
  11.  
  12. pub struct RegexpSearcher {
  13.     results: Vec<size_t>
  14. }
  15.  
  16. impl RegexpSearcher {
  17.     fn new() -> RegexpSearcher {
  18.         RegexpSearcher {
  19.             results: Vec::new(),
  20.         }
  21.     }
  22.    
  23.     fn search(&mut self, text: &str, regexp: &str) -> Vec<size_t> {
  24.         simple_regex::search(text, regexp)
  25.     }
  26.    
  27. /*    fn set_results(&mut self, results: Vec<size_t>) {
  28.         self.results = results;
  29.     }
  30. */    
  31. }
  32.  
  33. #[no_mangle]
  34. pub extern "C" fn createRegexpSearcher() -> *mut c_void {
  35.     Box::into_raw(Box::new(RegexpSearcher::new())) as *mut c_void
  36. }
  37.  
  38. #[no_mangle]
  39. pub extern "C" fn freeRegexpSearcher(ptr: *mut c_void) {
  40.     if ptr.is_null() {
  41.         return
  42.     }
  43.    
  44.     unsafe {
  45.         Box::from_raw(ptr);
  46.     }
  47. }
  48.  
  49. #[no_mangle]
  50. pub extern "C" fn search(ptr: *mut c_void, regexp: *const c_char, text:  *const c_char) -> *mut size_t {
  51.     let searcher = unsafe {
  52.         assert!(!ptr.is_null());
  53.         &mut *(ptr as *mut RegexpSearcher)
  54.     };
  55.     let text_c_str = unsafe {
  56.         assert!(!text.is_null());
  57.         CStr::from_ptr(text)
  58.     };
  59.     let text_str = text_c_str.to_str().unwrap();
  60.    
  61.     let regexp_c_str = unsafe {
  62.         assert!(!regexp.is_null());
  63.         CStr::from_ptr(regexp)
  64.     };
  65.     let regexp_str = regexp_c_str.to_str().unwrap();
  66.    
  67.     let ans = searcher.search(text_str, regexp_str);
  68.     searcher.results = ans;
  69.     let res = &searcher.results;
  70.     res.as_ptr() as *mut size_t
  71. }
  72.  
  73. #[cfg(test)]
  74. mod tests {
  75.     #[test]
  76.     fn it_works() {
  77.         assert_eq!(2 + 2, 4);
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement