我已经编写了一些与C/C++相关的FFI代码,
use libc::c_char;
use std::ffi::CString;
type arr_type = [c_char; 20]; // arr_type is the type in C
let mut arr : arr_type = [0; 20];
let s = "happy123";
let c_s = CString::new(s).unwrap();
let s_ptr = c_s.as_ptr();
如何使用字符串
arr
?在C / C ++中,我可以使用 memcpy
, strcpy
等 ...。我已经尝试了很多种方法,例如使用rlibc :: memcpy并发现它不能与libc一起使用...但编译器不允许我通过,关于Rust中的数组几乎没有信息。
添加: 阅读回复后,我想添加一些信息和更多问题。
1.
在C ++中,我使用
strcpy_s
将字符串复制到char数组中,因为字符串的长度和数组的大小都已知。我尝试了下面的两种方法。
std :: iter :: Zip
方法非常像 strcpy_s
,但我不知道是否有一些性能影响。
copy_nonoverlapping
方法使用 as_mut_ptr()
将数组转换为指针,然后没有长度信息,因为它位于 unsafe {}
块中,并且我尝试复制一个比数组更长的字符串,并且没有显示任何错误...我想知道那样行吗?并且在Rust中是否有类似于C ++中的strcpy_s的函数?
2.
我正在使用windows和msvc,对于char数组,我指的是
以下源文件都可以接受:
std::string s = "world is 世界";
std::wstring ws = L"world is 世界";
Qt:
QString qs = QStringLiteral("world is 世界");
Python 3:
s = 'world is 世界'
但在Rust中,以下内容可能是错误的吗?因为我在Eclipse调试窗口中看到了这个。
let s = "world is 世界";
我找到了rust-encoding并尝试了以下操作:
use encoding::{Encoding, EncoderTrap};
use encoding::all::GB18030;
let s = "world is 世界";
let enc = GB18030.encode(&s , EncoderTrap::Strict);
有没有更好的方式在Rust中实现?