Skip to content

Instantly share code, notes, and snippets.

@LivingInSyn
Last active December 11, 2020 03:17
Show Gist options
  • Save LivingInSyn/81395282fdeeb8257b60ff279e2a39b4 to your computer and use it in GitHub Desktop.
Save LivingInSyn/81395282fdeeb8257b60ff279e2a39b4 to your computer and use it in GitHub Desktop.
//using statements
use std::os::raw::c_char;
use std::ffi::CString;
//static var
static mut STRING_POINTER: *mut c_char = 0 as *mut c_char;
///structs
#[repr(C)]
pub struct SampleStruct {
pub field_one: i16,
pub field_two: i32,
pub string_field: *const c_char,
}
//private methods
fn store_string_on_heap(string_to_store: &'static str) -> *mut c_char {
//create a new raw pointer
let pntr = CString::new(string_to_store).unwrap().into_raw();
//store it in our static variable (REQUIRES UNSAFE)
unsafe {
STRING_POINTER = pntr;
}
//return the c_char
return pntr;
}
//public methods
#[no_mangle]
pub extern fn free_string() {
unsafe {
let _ = CString::from_raw(STRING_POINTER);
STRING_POINTER = 0 as *mut c_char;
}
}
#[no_mangle]
pub extern fn get_simple_struct() -> SampleStruct {
let test_string: &'static str = "Hi, I'm a string in rust";
let ptr = store_string_on_heap(test_string);
println!("{:p}",ptr);
SampleStruct {
field_one: 1,
field_two: 2,
string_field: ptr as *const c_char,
}
}
#[no_mangle]
pub extern fn add_numbers(number1: i32, number2: i32) -> i32 {
println!("Hello from rust!");
number1 + number2
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment