Converting (void*) to std::vector

前端 未结 4 2040
难免孤独
难免孤独 2021-01-07 22:31

I have a (void*) buffer that I need to convert to std::vector before I can pass it on. Unfortunately, my C++ casting skills a

4条回答
  •  被撕碎了的回忆
    2021-01-07 23:06

    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.

提交回复
热议问题