c++ size_type Converting(void*) to std::vector<unsigned char>

vector size_type (4)

I have a (void*) buffer that I need to convert to std::vector<unsigned char> before I can pass it on. Unfortunately, my C++ casting skills a little weak. Any suggestions?

The only time this would be legitimate is if you had already created a vector, and simply wanted to get it back.

void SomeFunc(void* input);

main() {
  std::vector< unsigned char > v;
  SomeFunc((void*) &v);

SomeFunc(void* input) {
  // Now, you could cast that void* into a vector
  std::vector< unsigned char >* v_ = (vector<unsigned char>*)input

I haven't actually tried to see if this will run, but that's the spirit of it. That said, if you are making this from scratch, you are definitely doing it wrong. This is really bad. The only time this could be even remotely understandable is if you are forced to implement the already defined "SomeFunc()".

using std::vector class for an already allocated buffer is not a solution. A std::vector object manages the memory and deallocates it at destruction time.

A complicated solution might be to write your own allocator, that uses an already allocated buffer, but you have to be very careful on several scenarios, like vector resizing, etc.

If you have that void* buffer bound through some C API functions, then you can forget about conversion to std::vector.

If you need only a copy of that buffer, it can be done like this:

std::vector< unsigned char> cpy( 
    (unsigned char*)buffer, (unsigned char*)buffer + bufferSize);

where bufferSize is the size in chars of the copied buffer.

You can't simply cast a void* to a std::vector<unsigned char> because the memory layout of the latter includes other objects, such as the size and the number of bytes currently allocated.

Assuming the buffer is pointed to by buf and its length is n:

vector<unsigned char> vuc(static_cast<char*>(buf), static_cast<char*>(buf) + n);

will create a copy of the buffer that you can safely use.

[EDIT: Added static_cast<char*>, which is needed for pointer arithmetic.]

You should not be doing any casting - full-stop. Please post some code that illustrates your question - I really don't understand what you mean by a "(void*) buffer".