File tree Expand file tree Collapse file tree 4 files changed +47
-4
lines changed Expand file tree Collapse file tree 4 files changed +47
-4
lines changed Original file line number Diff line number Diff line change @@ -3,18 +3,31 @@ void p();
3
3
void hello (const char * str );
4
4
char * repeat_hi (int times );
5
5
void free_cstr (const char * str );
6
+ int sum_of_positive (int * nums , size_t len );
7
+
8
+ typedef struct {
9
+ int x ;
10
+ int y ;
11
+ } Point ;
12
+
13
+ void print_point (Point point );
6
14
7
15
/*
8
16
static link:
9
- gcc main.c ../target/debug/libc_call_rust_lib.a
17
+ cargo build && gcc main.c ../target/debug/libc_call_rust_lib.a && ./a.out
10
18
dynamic link:
11
19
gcc main.c -Isrc -L ../target/debug/ -lc_call_rust_lib
12
20
*/
13
21
int main () {
14
22
p ();
15
23
hello ("rust" );
16
24
char * str = repeat_hi (3 );
17
- printf ("%s" , str );
25
+ printf ("%s\n " , str );
18
26
free_cstr (str );
27
+ int nums [3 ] = {1 , -1 , 3 };
28
+ int sum = sum_of_positive (nums , 3 );
29
+ printf ("sum = %d\n" , sum );
30
+ Point point = {.x = 1 , .y = 2 };
31
+ print_point (point );
19
32
return 0 ;
20
33
}
Original file line number Diff line number Diff line change
1
+ run : build
2
+ ./a.out
3
+ build :
4
+ cargo build && gcc main.c ../target/debug/libc_call_rust_lib.a
5
+ # clean:
6
+ # cargo clean && rm a.out
Original file line number Diff line number Diff line change 1
- use std:: os:: raw:: { c_char, c_int} ;
1
+ use std:: os:: raw:: { c_char, c_int, c_uint } ;
2
2
use std:: ffi:: { CStr , CString } ;
3
3
4
4
#[ no_mangle]
@@ -24,11 +24,35 @@ pub extern "C" fn repeat_hi(times: c_int) -> *mut c_char {
24
24
25
25
#[ no_mangle]
26
26
pub extern "C" fn free_cstr ( str : * mut c_char ) {
27
- // Rust的CStr交给C语言管理后,由于用的是堆内存, C语言并不会自动释放,所以还需要提供一个API去释放堆内存
27
+ // 在Rust函数内创建的堆内存变量, C语言并不会自动释放,所以还需要在Rust侧提供一个API去释放堆内存
28
28
if str. is_null ( ) {
29
29
return ;
30
30
}
31
31
unsafe {
32
32
CString :: from_raw ( str) ;
33
33
} ;
34
34
}
35
+
36
+ #[ no_mangle]
37
+ pub extern "C" fn sum_of_positive ( arr : * const c_int , len : c_uint ) -> c_int {
38
+ if arr. is_null ( ) {
39
+ return c_int:: from ( -1 ) ;
40
+ }
41
+ let nums = unsafe {
42
+ std:: slice:: from_raw_parts ( arr, len as usize )
43
+ } ;
44
+ let sum: i32 = nums. iter ( ) . filter ( |& x| x. is_positive ( ) ) . sum ( ) ;
45
+ c_int:: from ( sum)
46
+ }
47
+
48
+ #[ derive( Debug ) ]
49
+ #[ repr( C ) ]
50
+ pub struct Point {
51
+ x : i32 ,
52
+ y : i32 ,
53
+ }
54
+
55
+ #[ no_mangle]
56
+ pub extern "C" fn print_point ( point : Point ) {
57
+ dbg ! ( point) ;
58
+ }
You can’t perform that action at this time.
0 commit comments