Question

I have a const vector<uint8_t>>, and I need to pass it to a function that takes a const unsigned char*. The two types are the same size, etc., so I'm guessing that there is an good way to coerce the types here. What's the idiomatic way of handling this type of problem?

My first instinct is to use reinterpret_cast, but after the cast the data isn't the same. Here is my code:

shared_ptr<const vector<uint8_t>> data = operation.getData();
const unsigned char* data2 = reinterpret_cast<const unsigned char*>(&data);
myFunction(data2, data->size());

Chances are I've confused a pointer for a value here, but maybe my entire approach is incorrect.

Was it helpful?

Solution

reinterpret_cast is almost never the right solution, unless you know exactly what you’re doing, and even then usually not.

In your case, you just want a pointer to the contiguous data storage inside the vector (but not the vector itself, as you’ve noticed! That stores other data as well, such as the size & capacity). That’s easy enough, it’s the pointer of the first element of the data:

&vector[0]

So your code would look as follows:

myFunction(&(*data)[0], data->size());

OTHER TIPS

Just use vector<unsigned char> to begin with. On all platforms, unsigned char will have at least 8 bits. On platforms that have an 8-bit unsigned integral type, uint8_t will be a synonym for unsigned char; on platforms that do not have an 8-bit unsigned integral type, uint8_t will not exist, but unsigned char will.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top