Joo*_*ook 2 c++ type-conversion
我需要这种转换,因为我正在使用库并希望保留它们的定义,但必须使它们协同工作。
所以我有
functionX(uint8 *src, uint16 nSrcLen){
write(src);
}
write(const char msg){}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助;)
编辑:附加信息
functionX 和 write 应该,如果可能的话,保持这种方式。然而,无论如何,我对更好的解决方案感兴趣。
src将携带空字节
编辑:写,如何使用它
std::string hex_chars;
std::getline(std::cin, hex_chars);
std::istringstream hex_chars_stream(hex_chars);
unsigned int ch;
while (hex_chars_stream >> std::hex >> ch)
{
write(ch);
}
Run Code Online (Sandbox Code Playgroud)
现在,不再需要十六进制转换了,但我想仍然有必要使用这种流构造
编辑:当前解决方案
for(uint16 i = 0; i < nSrcLen; i++)
{
write(reinterpret_cast<unsigned char*>(src)[i]);
//printf("%d",reinterpret_cast<unsigned char*>(src)[i]);
}
Run Code Online (Sandbox Code Playgroud)
现在对我有用 - 谢谢你们!
要转换指针类型,您只需要将指针从一种类型转换为另一种类型。
例如,
uint8 *uint8_pointer = ?;
// C style cast
const char *char_pointer = (char*)uint8_pointer;
// newer C++ style cast syntax
const char *char_pointer2 = reinterpret_cast<char*>(uint8_pointer);
Run Code Online (Sandbox Code Playgroud)
你也可以反过来做:
char *char_pointer = ?;
uint8 *uint8_pointer = reinterpret_cast<uint8*>(char_pointer);
Run Code Online (Sandbox Code Playgroud)
对于您的功能,您可以使用:
functionX(uint8 *src, uint16 nSrcLen){
write(reinterpret_cast<char*>(src));
}
void write(const char* msg);
Run Code Online (Sandbox Code Playgroud)