Ημερήσια αρχεία: 29 Δεκεμβρίου 2017


Converting a (void*) buffer to a std::vector

On a project we were recently working on, some legacy C code was producing a (void*) voidBuffer accompanied by its size.
The rest of the project was in C++ and we needed to convert the (void*) voidBuffer to a std::vector<unsigned char> vector.

To do so, we used the following code:


//First cast the (void *) voidBuffer to an (unsigned char *) to implicitly get the element size (1 Byte each)
const unsigned char *charBuffer = (unsigned char *) voidBuffer;
//Then we create the vector (named vectorBuffer) by copying the contents of charBuffer to the vector
std::vector<unsigned char> vectorBuffer(charBuffer, charBuffer + length);

[download id=”4084″]