ffi.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //! FFI functions, only to be called from C.
  2. //!
  3. //! Equivalent C versions of these live in `src/common/compat_rust.c`
  4. use std::mem::forget;
  5. use std::ffi::CString;
  6. use libc;
  7. use rust_string::RustString;
  8. /// Free the passed `RustString` (`rust_str_t` in C), to be used in place of
  9. /// `tor_free`().
  10. ///
  11. /// # Examples
  12. /// ```c
  13. /// rust_str_t r_s = rust_welcome_string();
  14. /// rust_str_free(r_s);
  15. /// ```
  16. #[no_mangle]
  17. #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
  18. pub unsafe extern "C" fn rust_str_free(_str: RustString) {
  19. // Empty body: Just drop _str and we're done (Drop takes care of it).
  20. }
  21. /// Lends an immutable, NUL-terminated C String.
  22. ///
  23. /// # Examples
  24. /// ```c
  25. /// rust_str_t r_s = rust_welcome_string();
  26. /// const char *s = rust_str_get(r_s);
  27. /// printf("%s", s);
  28. /// rust_str_free(r_s);
  29. /// ```
  30. #[no_mangle]
  31. pub unsafe extern "C" fn rust_str_get(str: RustString) -> *const libc::c_char {
  32. let res = str.as_ptr();
  33. forget(str);
  34. res
  35. }
  36. /// Returns a short string to announce Rust support during startup.
  37. ///
  38. /// # Examples
  39. /// ```c
  40. /// rust_str_t r_s = rust_welcome_string();
  41. /// const char *s = rust_str_get(r_s);
  42. /// printf("%s", s);
  43. /// rust_str_free(r_s);
  44. /// ```
  45. #[no_mangle]
  46. pub extern "C" fn rust_welcome_string() -> RustString {
  47. let s = CString::new("Tor is running with Rust integration. Please report \
  48. any bugs you encouter.")
  49. .unwrap();
  50. RustString::from(s)
  51. }