使用C++检测Windows的架构(32位或64位)- wProcessorArchitecture显示错误结果

4
我使用以下代码来判断Windows是32位还是64位:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

static int is64bitOS()
{
    SYSTEM_INFO si;
    GetSystemInfo(&si);

    if((si.wProcessorArchitecture & PROCESSOR_ARCHITECTURE_IA64)||(si.wProcessorArchitecture & PROCESSOR_ARCHITECTURE_AMD64)==64)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    printf("%d\n", is64bitOS());
    return 0;
}

我购买并安装了64位的Windows 7 - 然而,上面的代码显示0,意味着我的操作系统是32位的...该怎么处理?
好的,我的其他尝试基本上也不起作用...在我的64位Windows 7上,我只看到32位...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>

int getArchType1()
{
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);

    switch(sysInfo.wProcessorArchitecture)
    {
    case 6:
        return 64;
    case 9:
        return 64;
    case 0:
        return 32;
    default:
        return -1;
    }
}

static char *getArchType2()
{
    char *archType = malloc(sizeof(char) * (255));
    memset(archType, '\0', 255);

#if defined _WIN64
    strcpy(archType, "64-bit");
#else
    strcpy(archType, "32-bit");
#endif // defined

    return archType;
}

int main()
{
    char *arch = getArchType1();
    printf("%s\n", arch);
    free(arch);
    printf("%d\n", getArchType2());
    char c;
    scanf("%c", &c);
    return 0;
}

1
你尝试将其构建为64位可执行文件了吗?如果使用32位可执行文件,我预计它会返回一个32位处理器,因为大多数应用程序不知道如果告诉它们它们没有编译的处理器该怎么办(同样适用于在Linux上询问处理器的代码,32位应用程序将被告知它们在32位处理器上,而不是64位处理器)。 - Mats Petersson
我正在使用Code::Blocks(单文件)构建我的代码,因此我猜默认是32位的。我应该在哪里更改它? - mirx
是的,允许32位代码在64位操作系统上运行的wow64模拟器做得非常令人信服 :) 试图打败它有点无意义,你应该只针对x64。在32位操作系统上永远不会有问题,有人搞错了那个。 - Hans Passant
布尔 OR 操作的结果不会等于 64。 - David Schwartz
1个回答

11

来自MSDN:

GetNativeSystemInfo函数

检索有关在WOW64下运行的应用程序的当前系统的信息。如果从64位应用程序调用该函数,则相当于GetSystemInfo函数。

GetSystemInfo的描述中,其中有一个提示:

要为在WOW64上运行的应用程序检索准确的信息,请调用GetNativeSystemInfo函数。

这基本上说明了你请求的是环境信息而不是真实的系统架构。

它还给出了另一个提示,在64位Windows上,可以同时运行Win32x64代码,这取决于你选择的平台。

另请参见:


我想出了这个解决方案:http://pastie.org/private/u6m3uqtcp6cswf0fkpa09a。它是否跨平台(适用于所有编译器(我主要关注GCC和VS)和Windows版本)? - mirx
不,这并不能获取操作系统的架构,因为你需要像上面提到的那样查询操作系统。 - Roman R.
哎呀,又写了一段代码:http://pastie.org/pastes/9146253/text?key=iq9rpcoqkz8fy7gtztretw 但是当编译它(我在32位操作系统上编译,然后在64位操作系统上运行*.exe)时,它只显示32位... - mirx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接