Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "cast" a std::vector<char> to std::vector<wchar_t>

Tags:

c++

stl

I have a std::vector of bytes (char), I'd like to do the equivalent of just "C-style casting" this vector to a vector which is of type wchar_t.

Obviously, what I really have to do is to copy the data, but the thing here is that I already have an UTF-16 byte stream on the left side, I just wanna move that over to the wchar_t vector so that I can use it. Ideally, I'd like to just swap the buffer, but I'm not sure how to do that in safe manner...

What's the C++ way of doing an as efficient as safe conversion copy operation allows?

NOTE:

I do store my UTF-16 strings as std::wstring or std::vector<wchar_t> but I have this memory buffer that I happen to know is UTF-16, and I need to copy it, somehow...

like image 301
John Leidegren Avatar asked Dec 06 '11 14:12

John Leidegren


3 Answers

The most efficient (and sanest) way to do it is to not do it. Let your vector<char> own the data buffer, and simply create a pair of wchar_t pointers to use as iterators pointing into the vector.

std::vector<char> vec;
wchar_t* first = reinterpret_cast<wchar_t*>(&vec[0]);
wchar_t* last = reinterpret_cast<wchar_t*>(&vec[0] + vec.size());

Now you have an iterator pair that'll work just fine with all the standard library algorithms. And you didn't have to copy a single byte. :)

(Disclaimer: I'm assuming that the vector's size is divisible by sizeof(wchar_t). Otherwise you'll have to adjust the last pointer)

like image 199
jalf Avatar answered Sep 26 '22 05:09

jalf


std::vector<char> v1;
std::vector<wchar_t> v2;

const char * cv1 = v1.data();

const wchar_t * cv2 = static_cast<const wchar_t *>(cv1);
std::copy(cv2, cv2 + v1.size() / sizeof(wchar_t), std::back_inserter(v2));
like image 40
emsr Avatar answered Sep 23 '22 05:09

emsr


std::vector<char> v1;
std::vector<wchar_t> v2;

wchar_t *begin = (wchar_t *) &v2.front();
wchar_t *end   = (wchar_t *) (&v2.back() + 1);

v1.assign(begin, end);

I haven't tested this, but I can't imagine that something like this wouldn't work... If you have endian issues, this would become quite a bit more complicated.

like image 26
Bill Lynch Avatar answered Sep 25 '22 05:09

Bill Lynch