简体   繁体   中英

Conversion from char* buffer to const uint8*

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)?

Option 1: Use reinterpret_cast, disobeying the disallowance.

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

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)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM