gpt4 book ai didi

rust - 从 Rust 向 C 函数提供 `char **` 参数?

转载 作者:行者123 更新时间:2023-11-29 08:23:31 25 4
gpt4 key购买 nike

我有一个(简化的)看起来像这样的 C 函数:

static char buffer[13];

void get_string(const char **s) {
sprintf(buffer, "Hello World!");
*s = buffer;
}

我已经在 Rust 中声明了它:

extern pub fn get_string(s: *mut *const c_char);

但我想不出调用它所需的咒语,并将结果转换为 Rust 字符串。我尝试过的所有方法要么无法编译,要么导致 SEGV。

有什么建议吗?

最佳答案

首先, char in Rust 等同于 char in C :

The char type represents a single character. More specifically, since 'character' isn't a well-defined concept in Unicode, char is a 'Unicode scalar value', which is similar to, but not the same as, a 'Unicode code point'.

在 Rust 中你可以使用 u8i8取决于操作系统。您可以使用 std::os::raw::c_char 为此:

Equivalent to C's char type.

C's char type is completely unlike Rust's char type; while Rust's type represents a unicode scalar value, C's char type is just an ordinary integer. This type will always be either i8 or u8, as the type is defined as being one byte long.

C chars are most commonly used to make C strings. Unlike Rust, where the length of a string is included alongside the string, C strings mark the end of a string with the character '\0'. See CStr for more information.

首先,我们需要一个可以传递给函数的变量:

let mut ptr: *const c_char = std::mem::uninitialized();

将其作为 *mut 传递你可以简单地使用引用:

get_string(&mut ptr);

现在使用 *const c_char用于创建 CStr :

let c_str = CStr::from_ptr(ptr);

将其转换为 String你可以选择:

c_str.to_string_lossy().to_string()

c_str().to_str().unwrap().to_string()

但是,您不应该使用 String如果你真的不需要。在大多数情况下,一个 Cow<str> 满足需求。可以通过c_str.to_string_lossy()获得:

If the contents of the CStr are valid UTF-8 data, this function will return a Cow::Borrowed([&str]) with the the corresponding [&str] slice. Otherwise, it will replace any invalid UTF-8 sequences with U+FFFD REPLACEMENT CHARACTER and return a Cow::[Owned](String) with the result.

您可以在 Playground 上看到这个 Action . This Playground显示了 to_string_lossy() 的用法.

关于rust - 从 Rust 向 C 函数提供 `char **` 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com