Home > Mobile >  Conversion from char* buffer to const uint8*
Conversion from char* buffer to const uint8*

Time:11-19

I have a quite big char* buffer (content of a file, read with streambuf sgetn). I need to pass it to an internal function, where const uint8* is required. How can I do this without reinterpret_cast (not allowed)?

CodePudding user response:

Option 1: Use reinterpret_cast, disobeying the disallowance.

Option 2: Change the premise, and start with an unsigned char (i.e. std::uint8_t) buffer instead of char buffer, so that there is no need to convert.

CodePudding user response:

With such a restriction, use casting to a desired pointer type through casting to void*. Any pointer can be casted to void* and it can be casted to any pointer (with keeping or making const if needed).

#include <cstdint>

void f(const uint8_t* p) {}

int main() {
  char p[] = "";
  f(static_cast<uint8_t*>(static_cast<void*>(p)));
}
  • Related