facet_samplelibc/
lib.rs

1#![allow(clippy::disallowed_names)]
2
3use facet::{Facet, PtrMut, Shape};
4
5unsafe extern "C" {
6    pub unsafe fn get_library_message() -> *const std::ffi::c_char;
7    pub unsafe fn get_foo() -> *mut Foo;
8}
9
10pub fn get_foo_and_shape() -> (PtrMut<'static>, &'static Shape) {
11    (unsafe { PtrMut::new(get_foo()) }, Foo::SHAPE)
12}
13
14pub fn print_global_foo() {
15    let foo = unsafe { get_foo() };
16    let bar = unsafe { &(*foo).bar };
17    let x = unsafe { (*foo).x };
18    let y = unsafe { (*foo).y };
19
20    println!("Foo: x={}, bar.a={}, bar.b={}, y={}", x, bar.a, bar.b, y);
21}
22
23#[derive(Facet, Debug)]
24#[repr(C)]
25pub struct Foo {
26    pub x: i64,
27    pub bar: Bar,
28    pub y: i64,
29}
30
31#[derive(Facet, Debug)]
32#[repr(C)]
33pub struct Bar {
34    pub a: i32,
35    pub b: i32,
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn message() {
44        if !cfg!(miri) {
45            let msg = unsafe { get_library_message() };
46            let c_str = unsafe { std::ffi::CStr::from_ptr(msg) };
47            let rust_str = c_str.to_string_lossy();
48            println!("{}", rust_str);
49
50            assert_eq!(rust_str, "IAMA C lib AMA")
51        }
52    }
53
54    #[test]
55    fn foo() {
56        if !cfg!(miri) {
57            print_global_foo();
58        }
59    }
60}