C与汇编混合编程,获得CPU家族信息

本文介绍了一段用于跨平台获取CPU信息的代码实现,适用于Intel或AMD CPU,并能在32位或64位的Windows及Linux环境下运行。通过调用CPUID指令,该程序能够收集并展示关于CPU的具体信息。

代码正确性尚未验证,仅测试用。


这段代码被设计为跨平台的,应该能够运行于这样的环境:

(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

运行结果:



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值