-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
257 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
use ffi_destruct::{extern_c_destructor, Destruct}; | ||
use std::ffi::*; | ||
|
||
#[derive(Destruct)] | ||
pub struct MyStruct { | ||
field: *mut std::ffi::c_char, | ||
} | ||
|
||
pub struct AnyOther(u32, u32); | ||
|
||
// Struct definition here, with deriving Destruct and nullable attributes. | ||
#[derive(Destruct)] | ||
pub struct Structure { | ||
// Default is non-null. | ||
c_string: *const c_char, | ||
#[nullable] | ||
c_string_nullable: *mut c_char, | ||
|
||
other: *mut MyStruct, | ||
#[nullable] | ||
other_nullable: *mut MyStruct, | ||
|
||
// Raw pointer for any other things | ||
any: *mut AnyOther, | ||
|
||
// Non-pointer types are still available, and will not be added to drop(). | ||
pub normal_int: u32, | ||
pub normal_string: String, | ||
} | ||
|
||
// (Optional) The macro here generates the destructor: destruct_structure() | ||
extern_c_destructor!(Structure); | ||
|
||
fn main() { | ||
let my_struct = Structure { | ||
c_string: CString::new("Hello").unwrap().into_raw(), | ||
c_string_nullable: std::ptr::null_mut(), | ||
other: Box::into_raw(Box::new(MyStruct { | ||
field: CString::new("Hello").unwrap().into_raw(), | ||
})), | ||
other_nullable: std::ptr::null_mut(), | ||
any: Box::into_raw(Box::new(AnyOther(1, 1))), | ||
normal_int: 114514, | ||
normal_string: "Hello".to_string(), | ||
}; | ||
|
||
let my_struct_ptr = Box::into_raw(Box::new(my_struct)); | ||
// FFI calling | ||
unsafe { | ||
destruct_structure(my_struct_ptr); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters