gpt4 book ai didi

c++ - Rust 中从 extern "C"方法返回动态字符串以供 C 或 C++ 使用的最佳方法

转载 作者:行者123 更新时间:2023-11-29 08:30:07 26 4
gpt4 key购买 nike

这个有点相关,但答案对我来说并不是很清楚: C library freeing a pointer coming from Rust

还有一个 example with static string在书中,但是它不能正确处理动态创建的字符串。

我最终找到了这个解决方案,其中调用 C/C++ 代码为要接收的字符串分配并稍后释放内存,但它看起来有些丑陋并且必须为未知字符串定义一些特定长度:

#[no_mangle]
pub extern fn rs_string_in_string_out(s_raw: *const c_char, out: *mut c_char) -> c_int {
// take string from the input C string
if s_raw.is_null() { return 0; }

let c_str: &CStr = unsafe { CStr::from_ptr(s_raw) };
let buf: &[u8] = c_str.to_bytes();
let str_slice: &str = std::str::from_utf8(buf).unwrap();
let str_buf: String = str_slice.to_owned();

//produce a new string
let result = String::from(str_buf + " append from Rust");
let len = result.len();

//create C string for output
let c_result = CString::new(result);

//write string into out pointer passed by C++ addon
unsafe{ std::ptr::copy(c_result.unwrap().as_ptr(), out, len); };

// return result length
return len as c_int;
}

如果有某种东西实际上返回一个值,而不是写入可变参数,那就太好了。

最佳答案

您可以使用 into_rawCString 上将其转换为原始指针,然后您可以从函数返回它。

你不应该依赖 Rust 使用系统分配器。无法保证您的 Rust 代码将链接到与 C/C++ 代码相同的 free。例如,在 Windows 上,有 msvcrtmsvcr80msvcr90 等,它们都管理单独的堆。因此,您的库仍应提供一个函数来释放它分配的内存。对于 CString,您应该使用 CString::from_raw为此(您不需要使用结果,Rust 会自动丢弃它,这将释放堆上的字符串)。

关于c++ - Rust 中从 extern "C"方法返回动态字符串以供 C 或 C++ 使用的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389886/

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