63 lines
1.1 KiB
Rust
63 lines
1.1 KiB
Rust
#![allow(dead_code)]
|
|
|
|
use std::ffi::{CStr, c_char};
|
|
|
|
fn say_hello(name: &str) {
|
|
println!("Hello from Rust, {name}!");
|
|
}
|
|
|
|
#[unsafe(no_mangle)]
|
|
extern "C" fn hello(c: *const c_char) -> () {
|
|
say_hello(unsafe { CStr::from_ptr(c) }.to_str().unwrap())
|
|
}
|
|
|
|
#[repr(C)]
|
|
#[derive(Debug)]
|
|
struct T {
|
|
a: bool,
|
|
b: u8,
|
|
}
|
|
|
|
#[unsafe(no_mangle)]
|
|
extern "C" fn hello_struct(t: T) -> () {
|
|
say_hello(&format!("{:?}", t))
|
|
}
|
|
|
|
#[repr(C)]
|
|
#[derive(Debug)]
|
|
enum Shape {
|
|
Circle { radius: f64 },
|
|
Rectangle { width: f64, height: f64 },
|
|
}
|
|
|
|
#[unsafe(no_mangle)]
|
|
extern "C" fn hello_shape(s: Shape) -> () {
|
|
say_hello(&format!("{:?}", s))
|
|
}
|
|
|
|
/// cbindgen:prefix=__attribute__((const))
|
|
#[unsafe(no_mangle)]
|
|
extern "C" fn add(a: i64, b: i64) -> i64 {
|
|
a + b
|
|
}
|
|
|
|
#[repr(C)]
|
|
#[derive(Clone, Copy)]
|
|
enum BTree {
|
|
Leaf {
|
|
value: i64,
|
|
},
|
|
Fork {
|
|
left: *const BTree,
|
|
right: *const BTree,
|
|
},
|
|
}
|
|
|
|
#[unsafe(no_mangle)]
|
|
extern "C" fn sum_tree(t: BTree) -> i64 {
|
|
match t {
|
|
BTree::Leaf { value } => value,
|
|
BTree::Fork { left, right } => unsafe { sum_tree(*left) + sum_tree(*right) },
|
|
}
|
|
}
|