Converting (void*) to std::vector

前端 未结 4 2042
难免孤独
难免孤独 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:11

    You can't simply cast a void* to a std::vector 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 vuc(static_cast(buf), static_cast(buf) + n);
    

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

    [EDIT: Added static_cast, which is needed for pointer arithmetic.]

提交回复
热议问题