转换为带和不带reinterpret_cast的字符串

convert to string with and without reinterpret_cast

本文关键字:cast 字符串 转换 reinterpret      更新时间:2023-10-16

我一直在寻找在Linux中获取CPUID的代码,并遇到了几个很好的例子。这些是实施差异之间的具体问题。下面是无符号整数,它使用 reinterpret_cast size_t为 12

struct CPUVendorID{
unsigned int ebx;
unsigned int edx;
unsigned int ecx;
string toString() const {
    return string(reinterpret_cast<const char *>(this), 12);
}
};
...
CPUVendorID vendorID { .ebx = ebx, .edx = edx, .ecx = ecx };
string vendor = vendorID.toString();

下面给出了另一种形式,以获得与 4 size_t相同的输出:

string vendor;
vendor += string((const char *)&cpuID.EBX(), 4);
vendor += string((const char *)&cpuID.EDX(), 4);
vendor += string((const char *)&cpuID.ECX(), 4);
cout << "CPU vendor = " << vendor << endl;

两者都输出 12 个字符的字符串。有人可以解释一下上面reinterpret_cast声明中发生了什么吗?我觉得这种实现方式非常优雅,但我不知道为什么它明显地工作 4*3=12。但是,它如何设法连接来自 3 ebx、edx 和 ecx 的数据?

CPU 的制造商 ID 字符串 – 存储在 EBX、EDX、ECX 中的十二个字符的 ASCII 字符串(按此顺序) CPUID wiki

有人可以解释一下上面reinterpret_cast声明中发生了什么吗?

结构地址this与其第一个成员的地址一致,即 int ebx 。由于以下成员属于同一类型,因此它们之间没有填充,因此此代码将三个int成员视为int[3]数组。