c++ - 如何安全地将 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++:
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
它来安全地包装指针。
推荐阅读
- oracle - Oracle PL/SQL 变量使用导致 SQL 开发人员出错
- python - 检查Python中的3d数组中是否存在2d数组?
- sql - SQL Server - 对子查询中的时间戳日期字段进行排序,然后格式化以供查看
- c# - Recipients.ResolveAll 一半失败
- react-native - 运行弹出时出错:错误:连接已禁用
- python-3.x - 在 python 中使用 mpmath 绘图时如何标记轴?
- html - Html中的嵌套类,最里面的类的Css样式
- php - PHPMailler 错误(页面无法显示,因为发生了内部服务器错误。)
- spring-integration - 调用 SimpleWebServiceInboundGateway.invoke 方法时出错
- javascript - 学习测试Vue.js项目:产品展示列表