Search code examples
c++constantsstdvector

Cast const std::vector<char> to unsigned char*?


Writing a C++ wrapper for a C library. In the library there is a function which accepts a buffer as unsigned char *. Since working with C++ I store my real buffer in std::vector<char>, moreover, in the wrapper class I also added const, because the buffer in question is an input buffer and it wont get modified. But my code does not compile, demo:

#include <stdio.h>
#include <vector>

void x(unsigned char *s)
{
    printf("%s\n", s);
}

int main()
{
    const std::vector<char> s(10);

    x(reinterpret_cast<unsigned char *>(s.data())); // FAILS
}

What is wrong with id? If I remove the consts from const std::vector<char> s(10); it works, but I would prefer it that way.


Solution

  • Your error is because you declare your std::vector as const.

    If you drop the constness, it works properly. (As seen here)

    Anyway, you should ask yourself if you really need to store chars or unsigned chars in your array.

    If you want to keep the const, you would have to use a const_cast but your line would become pretty long :

    x(const_cast<unsigned char*>(reinterpret_cast<const unsigned char *>(s.data())));

    If you have access to the library, it would have been better to mark the buffer as const if it isn't changed. But, since it isn't const, you can't be sure it won't be modifier by the function and, because of that, you shouldn't keep your std::vector as a const.