代码正确性尚未验证,仅测试用。
这段代码被设计为跨平台的,应该能够运行于这样的环境:
(1) 采用Intel或AMD的不低于80486级别的CPU的计算机;
(2) 操作系统环境为32位或64位的Windows或Linux/Unix。
代码:
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long DWORD;
DWORD _eax; // value eax after cpuid
DWORD _ebx; // value ebx after cpuid
DWORD _ecx; // value ecx after cpuid
DWORD _edx; // value edx after cpuid
/* ==========================================================================
* Execute the 'cpuid' instruction.
* --------------------------------------------------------------------------
* ==========================================================================
*/
void ExecuteCpuid(DWORD veax)
{
// The following 4 DWORD variable store the four registers values after cpuid
DWORD deax;
DWORD debx;
DWORD decx;
DWORD dedx;
__asm
{
mov eax, veax
cpuid
mov deax, eax
mov debx, ebx
mov decx, ecx
mov dedx, edx
}
_eax = deax; // store in class member
_ebx = debx;
_ecx = decx;
_edx = dedx;
}
void LeftMove(DWORD v, DWORD *vx)
{
for (int i = 0; i < 3; i++)
{
v = (v >> i);
vx[i] = v;
}
}
void GetCpuidString(char **idString, size_t* pLength)
{
DWORD ax[3];
DWORD bx[3];
DWORD cx[3];
DWORD dx[3];
ExecuteCpuid(1);
LeftMove(_eax, ax);
LeftMove(_ebx, bx);
LeftMove(_ecx, cx);
LeftMove(_edx, dx);
*pLength = 100;
*idString = malloc(100);
sprintf_s(
*idString, *pLength,
"%0X%0X%0X%0X%0X%0X%0X%0X%0X%0X%0X%0X",
ax[0], ax[1], ax[2],
bx[0], bx[1], bx[2],
cx[0], cx[1], cx[2],
dx[0], dx[1], dx[2]);
}
int main(int argc, char* argv[])
{
char *idString = NULL;
size_t length;
GetCpuidString(&idString, &length);
printf("cpuid is 0x%s\n", idString);
if (idString)
{
free(idString);
idString = NULL;
}
return 0;
}
实际测试条件:
- OS:Windows 8.1 64位
- Visual Studio 2013
- Hardware:Thinkpad T400
运行结果: