gpt4 book ai didi

c++ - 如何安全地将 C++ 字符串传递给 Rust?

转载 作者:行者123 更新时间:2023-12-01 14:31:04 30 4
gpt4 key购买 nike

我有这个 Rust 函数:

pub extern "C" fn do_something(my_string: &str) {
let s = String::from(my_string);
}

我用这个调用 C++:
std::string my_string("hello");
do_something(my_string.c_str());

签名:
extern "C" void* do_something(const char*);

我在 String::from 行上收到此错误:
memory allocation of 127963177044160 bytes failedAborted (core dumped)

我猜这是因为传递的字符串没有 \n 所以它试图使一个最大大小的字符串成为可能。

如何安全地将 std::string 传递给 Rust?

最佳答案

That I call on C++ with this:

do_something(my_string.c_str());

因此,在 C++ 方面,您使用 C 字符串作为输入调用函数(不是 std::string ,这是一个非常相关的区别)。
这意味着 Rust 函数应该将 C 字符串作为输入,而 &str 绝对不是。
因此 do_something 应声明为:
pub extern "C" fn do_something(my_string: *const c_char) {
接下来,正如 Jmb 所指出的,您可能希望使用 CStr 来安全地包装指针。

关于c++ - 如何安全地将 C++ 字符串传递给 Rust?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62400700/

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