c++ - 从 reinterpret_cast 获取原始 char* 值

标签 c++ casting reinterpret-cast

请考虑以下代码:

const char* cTitle = "MyTitle";
__int64 i = reinterpret_cast<__int64>(ctitle);

每次我运行这段代码,我都会得到不同的i值。 现在我想编写一个测试来检查我们是否发送了正确的标题,所以我使用以下代码来实现目标但无法使用 reinterpret_cast 获取标题:

char* cOrgValue = reinterpret_cast<char*> (i);

是否有可能获得原始标题值,如果有,那么这是正确的做法吗?

编辑

那么让我重新表述一下这个问题: 在使用 reinterpret_cast 将其转换为 __int64 后,如何获取 char* 的原始值。

最佳答案

Don't use reinterpret_cast .这是我的建议。相反,请调用 std::memcpy :

const char cTitle[] = "MyTitle";
std::uint64_t i64 = 0;
static_assert(sizeof(cTitle) >= sizeof(i64), "wrong sizes");
std::memcpy(&i64, cTitle, sizeof(i64));

您通过对 memcpy 的反向调用获得原始值。

注意:为了让 sizeof(cTitle)8(相关部分:读取字符串中char的个数,包括最后的\0)。对于 const char*sizeof(cTitle) 将是 sizeof(void*),这是未指定的。

关于c++ - 从 reinterpret_cast 获取原始 char* 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47769767/

相关文章:

go - 如何在golang中将bool转换为int8

c++ - 转换之间的数据丢失

c++ - 重新解释强制转换为不同类型的C++

c++ - 将类对象指针打包成 char * 用于消息队列

c++ - 当纵横比不是 1 时,光线追踪会给我扭曲的图像

c++ - 在 fstream c++ 的 while 循环中使用多个定界符

android - React-Native android NDK

c++ - 使用 "&"的令人费解的 C++ 语法

c - 是否由于类型转换未定义行为导致负载未对齐?

c++ - 将 reinterpret_cast 转换为可变大小的数组