要实现一个跨平台的 C++ 代码来检测当前环境是否为虚拟机,可以结合多种方法。以下是一个示例,使用 CPUID 和操作系统特定的检查来实现跨平台支持:
#include <iostream>
#include <string>
#if defined(_WIN32) || defined(_WIN64)
#include <intrin.h>
#else
#include <cpuid.h>
#include <fstream>
#endif
bool is_virtual_machine() {
#if defined(_WIN32) || defined(_WIN64)
int cpuInfo[4];
__cpuid(cpuInfo, 1);
return (cpuInfo[2] & (1 << 31)) != 0; // Check hypervisor flag
#else
unsigned int eax, ebx, ecx, edx;
__get_cpuid(1, &eax, &ebx, &ecx, &edx);
// Check hypervisor flag
if (eax & (1 << 31)) {
return true;
}
// Additional check for Linux
std::ifstream cpuinfo("/proc/cpuinfo");
std::string line;
while (std::getline(cpuinfo, line)) {
if (line.find("hypervisor") != std::string::npos) {
return true;
}
}
#endif
return false;
}
windows下更详细的信息,可以读注册表 计算机\HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\BIOS
下面有SystemFamily,如果是虚拟机/云桌面,它显示的一般都是"Virtual Machine",否则显示的是“QingYun”之类的