File tree Expand file tree Collapse file tree 3 files changed +29
-4
lines changed Expand file tree Collapse file tree 3 files changed +29
-4
lines changed Original file line number Diff line number Diff line change 2
2
.idea
3
3
.DS_Store
4
4
Cargo.lock
5
+ * .out
Original file line number Diff line number Diff line change
1
+ #include <stdio.h>
1
2
void p ();
2
3
void hello (const char * str );
4
+ char * repeat_hi (int times );
5
+ void free_cstr (const char * str );
3
6
4
7
/*
5
- static link: gcc main.c ../target/debug/libc_call_rust_lib.a
6
- dynamic link: gcc main.c -Isrc -L ../target/debug/ -lc_call_rust_lib
8
+ static link:
9
+ gcc main.c ../target/debug/libc_call_rust_lib.a
10
+ dynamic link:
11
+ gcc main.c -Isrc -L ../target/debug/ -lc_call_rust_lib
7
12
*/
8
13
int main () {
9
14
p ();
10
15
hello ("rust" );
16
+ char * str = repeat_hi (3 );
17
+ printf ("%s" , str );
18
+ free_cstr (str );
11
19
return 0 ;
12
20
}
Original file line number Diff line number Diff line change 1
1
use std:: os:: raw:: { c_char, c_int} ;
2
- use std:: ffi:: CStr ;
2
+ use std:: ffi:: { CStr , CString } ;
3
3
4
4
#[ no_mangle]
5
5
pub extern "C" fn p ( ) {
@@ -8,11 +8,27 @@ pub extern "C" fn p() {
8
8
9
9
#[ no_mangle]
10
10
pub extern "C" fn hello ( name : * const c_char ) {
11
+ assert ! ( !name. is_null( ) ) ;
11
12
let c_str = unsafe {
12
13
CStr :: from_ptr ( name)
13
14
} ;
14
15
println ! ( "hello {:?}" , c_str) ;
15
16
}
16
17
17
18
#[ no_mangle]
18
- pub extern "C" fn repeat_hi ( )
19
+ pub extern "C" fn repeat_hi ( times : c_int ) -> * mut c_char {
20
+ let mut res = String :: new ( ) ;
21
+ res. extend ( std:: iter:: repeat ( "hi" ) . take ( times as usize ) ) ;
22
+ CString :: new ( res) . unwrap ( ) . into_raw ( )
23
+ }
24
+
25
+ #[ no_mangle]
26
+ pub extern "C" fn free_cstr ( str : * mut c_char ) {
27
+ // Rust的CStr交给C语言管理后,由于用的是堆内存,C语言并不会自动释放,所以还需要提供一个API去释放堆内存
28
+ if str. is_null ( ) {
29
+ return ;
30
+ }
31
+ unsafe {
32
+ CString :: from_raw ( str) ;
33
+ } ;
34
+ }
You can’t perform that action at this time.
0 commit comments