Crates.io | theus |
lib.rs | theus |
version | 0.1.1 |
source | src |
created_at | 2024-09-04 23:05:44.683773 |
updated_at | 2024-09-04 23:05:44.683773 |
description | A procedural macro for generating C-compatible functions from Rust structs and traits |
homepage | |
repository | https://github.com/yourusername/theus |
max_upload_size | |
id | 1363949 |
size | 23,980 |
Welding Rust to other languages. Theus is a procedural macro for seamlessly generating C-compatible functions from Rust structs and traits.
impl Struct
blocks and impl Trait for Struct
blocks.&mut self
instead of &self
for all methods (never know what external code will do with your pointers)Add this to your Cargo.toml
:
[dependencies]
theus = "0.1.0"
Then, in your Rust code:
use theus::c_compatible;
struct MyStruct {
value: i32,
}
#[c_compatible]
impl MyStruct {
pub fn create(value: i32) -> Self {
MyStruct { value }
}
pub fn get_value(&mut self) -> i32 {
self.value
}
// Note the owned receiver. The struct
// will be dropped by the borrow checker
// once this function finishes execution
pub fn destroy(self) {}
}
trait MyTrait {
fn trait_method(&mut self, x: i32) -> i32;
}
#[c_compatible]
impl MyTrait for MyStruct {
fn trait_method(&mut self, x: i32) -> i32 {
self.value + x
}
}
Theus will generate the following code at compile time. When you compile
this to a cdylib
, it can be used with any C-compatible interface.
#[no_mangle]
pub unsafe extern "C" fn mystruct_create() -> *mut MyStruct {
Box::into_raw(Box::new(MyStruct::create()))
}
#[no_mangle]
pub extern "C" fn mystruct_get_value(ptr: *mut MyStruct) -> i32 {
(unsafe { &mut *ptr }).get_value()
}
#[no_mangle]
pub extern "C" fn mystruct_destroy(ptr: *mut MyStruct) {
unsafe { Box::from_raw(ptr) }.destroy()
}
#[no_mangle]
pub extern "C" fn mystruct_mytrait_trait_method(ptr: *mut MyStruct, x: i32) -> i32 {
(unsafe { &mut *ptr }).trait_method(x)
}
Miss Gladys Theus in 1945, one of the fastest and most efficient welders at the Kaiser Company Permanente Metals Corporation yards of Richmond, California. She is sticking to her job until final victory is won.
- National Archives and Records Administration, Washington, US.