@@ -22,37 +22,46 @@ You can find more information about using Rust from other languages in
2222Creating FFIs to use a Rust's ` struct ` methods from C or C++:
2323
2424``` rust
25- struct TestIt { value : u8 }
25+ struct Counter { value : u8 }
2626
27- impl TestIt {
27+ impl Counter {
28+ pub fn new () -> Self { Self { value : 0 } }
2829 pub fn add (& mut self , value : u8 ) { self . value += value }
2930 pub fn get (& self ) -> u8 { self . value }
3031}
3132
3233/// Ownership will NOT control the heap-allocated memory until own it back.
3334#[no_mangle]
34- pub extern fn test_it_new (value : u8 ) -> * mut TestIt {
35- return opaque_pointer :: raw (TestIt { value } );
35+ pub extern fn counter_new (value : u8 ) -> * mut TestIt {
36+ return opaque_pointer :: raw (Counter :: new () );
3637}
3738
38- /// Drop (free memory of) Rust's TestIt object as usually.
39+ /// Drop (free memory of) Rust's Counter object as usually.
3940#[no_mangle]
40- pub extern fn test_it_free ( test_it : * mut TestIt ) {
41- let test_it = unsafe { opaque_pointer :: free (test_it ) };
41+ pub extern fn counter_free ( counter : * mut Counter ) {
42+ unsafe { opaque_pointer :: free (counter ) };
4243}
4344
4445#[no_mangle]
45- pub extern fn test_it_add (test_it : * mut TestIt , value : u8 ) -> Result <(), opaque_pointer :: error :: PointerError > {
46- let test_it = unsafe { opaque_pointer :: mut_object (test_it )? };
47- test_it . add (value );
46+ pub extern fn counter_add (counter : * mut Counter , value : u8 ) -> boolean {
47+ let counter = unsafe { opaque_pointer :: mut_object (counter ) };
48+ if counter . is_err () {
49+ return false ;
50+ }
51+ let counter = counter . unwrap ();
52+ counter . add (value );
4853 // Here will NOT be dropped, the pointer continues been valid.
49- return Ok (()) ;
54+ return true ;
5055}
5156
5257#[no_mangle]
53- pub extern fn test_it_get (test_it : * const TestIt ) -> Result <u8 , opaque_pointer :: error :: PointerError > {
54- let test_it = unsafe { opaque_pointer :: object (test_it )? };
55- return Ok (test_it . get ());
58+ pub extern fn counter_get (counter : * const Counter ) -> u8 {
59+ let counter = unsafe { opaque_pointer :: object (counter ) };
60+ if counter . is_err () {
61+ return 0 ;
62+ }
63+ let counter = counter . unwrap ();
64+ return counter . get ();
5665 // Here will NOT be dropped, the pointer continues been valid.
5766}
5867```
0 commit comments