@@ -22,37 +22,46 @@ You can find more information about using Rust from other languages in
22
22
Creating FFIs to use a Rust's ` struct ` methods from C or C++:
23
23
24
24
``` rust
25
- struct TestIt { value : u8 }
25
+ struct Counter { value : u8 }
26
26
27
- impl TestIt {
27
+ impl Counter {
28
+ pub fn new () -> Self { Self { value : 0 } }
28
29
pub fn add (& mut self , value : u8 ) { self . value += value }
29
30
pub fn get (& self ) -> u8 { self . value }
30
31
}
31
32
32
33
/// Ownership will NOT control the heap-allocated memory until own it back.
33
34
#[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 () );
36
37
}
37
38
38
- /// Drop (free memory of) Rust's TestIt object as usually.
39
+ /// Drop (free memory of) Rust's Counter object as usually.
39
40
#[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 ) };
42
43
}
43
44
44
45
#[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 );
48
53
// Here will NOT be dropped, the pointer continues been valid.
49
- return Ok (()) ;
54
+ return true ;
50
55
}
51
56
52
57
#[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 ();
56
65
// Here will NOT be dropped, the pointer continues been valid.
57
66
}
58
67
```
0 commit comments