首页 > 解决方案 > 如何安全地将 C++ 字符串传递给 Rust?

问题描述

我有这个 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,所以它试图使字符串尽可能地具有最大大小。

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

标签: c++rust

解决方案


我用这个调用 C++:

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它来安全地包装指针。


推荐阅读