【发布时间】:2021-01-20 03:57:50
【问题描述】:
我一直在尝试使用多个字符串参数从 C 中调用 Rust 函数,但由于某种原因,唯一发送的参数是第一个。这是我尝试过的:
输入.c
extern void print_str(char str1, char str2);
void c_function() {
scanf("%s %s", str1, str2);
print_str(str1, str2);
}
lib.rs:
#[no_mangle]
pub extern "C" fn print_str(str1: &str, str2: &str) {
unsafe {
libc::printf(str1.as_ptr() as *const libc::c_char);
libc::printf(str2.as_ptr() as *const libc::c_char);
}
}
【问题讨论】:
-
Rust 代码 issues a warning: "
externfn 使用类型str,这不是 FFI 安全的" 建议:"考虑使用*const u8和一个长度,字符串切片没有 C 等效项" -
并且,在 C 中,
char与const char *不同。您打算提供字符串,但您的 C 声明需要两个 single 字符。