请考虑以下代码:
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/