Skip to content

Commit 0b673d5

Browse files
committed
use dbg! to print struct from c
1 parent b5f917a commit 0b673d5

File tree

4 files changed

+47
-4
lines changed

4 files changed

+47
-4
lines changed

c_call_rust_lib/a.out

-1.81 MB
Binary file not shown.

c_call_rust_lib/main.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,31 @@ void p();
33
void hello(const char *str);
44
char *repeat_hi(int times);
55
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);
614

715
/*
816
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
1018
dynamic link:
1119
gcc main.c -Isrc -L ../target/debug/ -lc_call_rust_lib
1220
*/
1321
int main() {
1422
p();
1523
hello("rust");
1624
char* str = repeat_hi(3);
17-
printf("%s", str);
25+
printf("%s\n", str);
1826
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);
1932
return 0;
2033
}

c_call_rust_lib/makefile

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
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

c_call_rust_lib/src/lib.rs

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::os::raw::{c_char, c_int};
1+
use std::os::raw::{c_char, c_int, c_uint};
22
use std::ffi::{CStr, CString};
33

44
#[no_mangle]
@@ -24,11 +24,35 @@ pub extern "C" fn repeat_hi(times: c_int) -> *mut c_char {
2424

2525
#[no_mangle]
2626
pub extern "C" fn free_cstr(str: *mut c_char) {
27-
// Rust的CStr交给C语言管理后,由于用的是堆内存,C语言并不会自动释放,所以还需要提供一个API去释放堆内存
27+
// 在Rust函数内创建的堆内存变量,C语言并不会自动释放,所以还需要在Rust侧提供一个API去释放堆内存
2828
if str.is_null() {
2929
return;
3030
}
3131
unsafe {
3232
CString::from_raw(str);
3333
};
3434
}
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+
}

0 commit comments

Comments
 (0)