I have write some FFI code to C/C++,
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();
How can I update arr with the String s? In C/C++ I can use memcpy, strcpy etc...
I have tried many, like use rlibc::memcpy and found it can't be used with libc.. , but the compiler don't let me pass, there is very few info about array in Rust.
Add: After read the replys, I want to add some info and more question.
1.
In C++, I use strcpy_s to copy string to char array, cause the length of string and the size of array are all known.
I have tried both methods below.
the std::iter::Zip method, seems very like strcpy_s, but I don't know if there is some performance affect.
the copy_nonoverlapping method, it use as_mut_ptr() cast the array to pointer then there is no length info, since it is in unsafe { } block, and I have tried copy a string longer then the array and there is no error displays... I wonder if that's ok?
And is there a function in Rust like strcpy_s in C++?
2.
I'm using windows and msvc, for the char array, I mean not deal with encoding or use default codepage encoding.
below are all ok in source file:
C++:
std::string s = "world is 世界";
std::wstring ws = L"world is 世界";
Qt:
QString qs = QStringLiteral("world is 世界");
Python 3:
s = 'world is 世界'
But in Rust, below may be wrong? as I see in Eclipse Debug window.
let s = "world is 世界";
I found rust-encoding and tried these:
use encoding::{Encoding, EncoderTrap};
use encoding::all::GB18030;
let s = "world is 世界";
let enc = GB18030.encode(&s , EncoderTrap::Strict);
Is there any better way to do in Rust?