DEVELOPMENT ENVIRONMENT

~liljamo/hare-rust-ffi-test

hare-rust-ffi-test/hello/src/lib.rs -rw-r--r-- 615 bytes
b76de4b1Jonni Liljamo feat: init 4 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use std::ffi::{CString, CStr};
use std::os::raw::c_char;

#[unsafe(no_mangle)]
pub extern "C" fn hello(s_ptr: *const c_char) -> *const c_char {
    let s = unsafe { CStr::from_ptr(s_ptr) }.to_str().expect("invalid UTF-8");
    CString::new(format!("Hello {}!", s)).unwrap().into_raw()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let ptr = hello(CStr::from_bytes_with_nul(b"Rust\0").unwrap().as_ptr());
        let out = unsafe { CStr::from_ptr(ptr) };
        let expected = CStr::from_bytes_with_nul(b"Hello Rust!\0").unwrap();
        assert_eq!(out, expected);
    }
}