__cpuidex读取CPU序列号
近日研究__cpuidex的用法,查询到的相关示例都比较复杂,所以本人简化了一部分内容,重新写了一个简单的例子,仅获取CPU序列号,最终结果与通过WMIC命令查询的结果保持一致。
代码示例
#include <iostream>
#include <array>
#include <intrin.h>
#include <vector>
#include <cstring>
using std::cout;
int main()
{
std::array<int, 4> cpui; //#include <array>
// Calling __cpuid with 0x0 as the function_id argument
// gets the number of the highest valid function ID. 什么是function ID?
__cpuid(cpui.data(), 0x0); //cpui[0] = "funcition_id的最大值"
int nIds_ = cpui[0];
std::vector<std::array<int, 4>> data_; //保存遍历到的所有cpui的值
for (int i=0;i<=nIds_;++i)
{
__cpuidex(cpui.data(), i, 0);
data_.push_back(cpui);
}
//reinterpret_cast<int*>(vendor) //*reinterpret_cast<int*>(vendor)
//索引0 0+4 0+8的值构成了CPU芯片的名称
char vendor[0x20] = { 0 };
*reinterpret_cast<int*>(vendor) = data_[0][1];
*reinterpret_cast<int*>(vendor + 4) = data_[0][3];
*reinterpret_cast<int*>(vendor + 8) = data_[0][2]; // vendor="GenuineIntel"
std::string vendor_ = vendor;
bool isIntel_ = false;
bool isAMD = false;
if ("GenuineIntel" == vendor_)
{
isIntel_ = true; //厂商为INTEL
}
else if ("AuthenticAMD"==vendor_)
{
isAMD = true; //厂商为AMD
}
char vendor_serialnumber[0x14] = { 0 };
sprintf_s(vendor_serialnumber, sizeof(vendor_serialnumber), "%08X%08X", data_[1][3], data_[1][0]);
//用“wmic cpu get processorid”获取的结果进行比对,结果应该是一致的。 //vendor_serialnumber = "BFEBFBFF000406E3";
std::cout << "ProcessorId is [ " << vendor_serialnumber << " ]" << std::endl;
return 0;
}
Microsoft Specific
Generates the cpuid instruction that is available on x86 and x64. This instruction queries the processor for information about supported features and the CPU type.
Syntax
void __cpuid(
int cpuInfo[4],
int function_id
);
void __cpuidex(
int cpuInfo[4],
int function_id,
int subfunction_id
);
Parameters
[out] cpuInfo
An array of four integers that contains the information returned in EAX, EBX, ECX, and EDX about supported features of the CPU.
[in] function_id
A code that specifies the information to retrieve, passed in EAX.
[in] subfunction_id
An additional code that specifies information to retrieve, passed in ECX.
Requirements
Header file <tintrin.h>
参考文献
其他
2017-3-14 10:58:23,更新函数说明。尖括号需要转义【<+分号】【>+分号】。
2017-2-14 14:39:04,上海宝山。