我有这个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传递给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
之后才能安全地包装指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句