实现" IsProcessorFeaturePresent"在C ++上

时间:2017-05-04 23:50:17

标签: c++ windows

帮助请将一小段代码从C#重新编译为C ++

class Program
{
    static void Main(string[] args)
    {
        foreach (ProcessorFeature feature in System.Enum.GetValues(typeof(ProcessorFeature)))
        {
            System.Console.WriteLine(feature.ToString() + "\t: " + IsProcessorFeaturePresent(feature));
        }
    }

    [System.Runtime.InteropServices.DllImport("Kernel32")]
    static extern bool IsProcessorFeaturePresent(ProcessorFeature processorFeature);

    enum ProcessorFeature : uint
    {
        PF_FLOATING_POINT_PRECISION_ERRATA = 0,
        PF_FLOATING_POINT_EMULATED = 1,
        PF_COMPARE_EXCHANGE_DOUBLE = 2,
        PF_MMX_INSTRUCTIONS_AVAILABLE = 3,
        PF_PPC_MOVEMEM_64BIT_OK = 4,
        PF_ALPHA_BYTE_INSTRUCTIONS = 5,
        PF_XMMI_INSTRUCTIONS_AVAILABLE = 6,
        PF_3DNOW_INSTRUCTIONS_AVAILABLE = 7,
        PF_RDTSC_INSTRUCTION_AVAILABLE = 8,
        PF_PAE_ENABLED = 9,
        PF_XMMI64_INSTRUCTIONS_AVAILABLE = 10,
        PF_SSE_DAZ_MODE_AVAILABLE = 11,
        PF_NX_ENABLED = 12,
        PF_SSE3_INSTRUCTIONS_AVAILABLE = 13,
        PF_COMPARE_EXCHANGE128 = 14,
        PF_COMPARE64_EXCHANGE128 = 15,
        PF_CHANNELS_ENABLED = 16,
        PF_XSAVE_ENABLED = 17,
        PF_SECOND_LEVEL_ADDRESS_TRANSLATION = 20,
        PF_VIRT_FIRMWARE_ENABLED = 21,
    }
}

我试图创建一个枚举,但编译器写了#34;需要一个标识符"。
编译器写道," winnt.h"

中已经有了一个定义
#define PF_FLOATING_POINT_PRECISION_ERRATA   0

我按照msdn中所述连接了库。

#include <winnt.h>
#pragma comment (lib, "Kernel32.lib")

我甚至不知道&#34; foreach&#34;在C ++上实现。

1 个答案:

答案 0 :(得分:1)

因为C ++没有反射,所以访问枚举的名称看起来很困难。但是字符串化运算符非常合适:

#define VAL_AND_NAME(x) { x, #x }
struct { int val; const char* name; } const features[] = {
    VAL_AND_NAME(PF_FLOATING_POINT_PRECISION_ERRATA),
    VAL_AND_NAME(PF_FLOATING_POINT_EMULATED),
    VAL_AND_NAME(PF_COMPARE_EXCHANGE_DOUBLE),
    VAL_AND_NAME(PF_MMX_INSTRUCTIONS_AVAILABLE),
    VAL_AND_NAME(PF_PPC_MOVEMEM_64BIT_OK),
    VAL_AND_NAME(PF_ALPHA_BYTE_INSTRUCTIONS),
    VAL_AND_NAME(PF_XMMI_INSTRUCTIONS_AVAILABLE),
    VAL_AND_NAME(PF_3DNOW_INSTRUCTIONS_AVAILABLE),
    VAL_AND_NAME(PF_RDTSC_INSTRUCTION_AVAILABLE),
    VAL_AND_NAME(PF_PAE_ENABLED),
    VAL_AND_NAME(PF_XMMI64_INSTRUCTIONS_AVAILABLE),
    VAL_AND_NAME(PF_SSE_DAZ_MODE_AVAILABLE),
    VAL_AND_NAME(PF_NX_ENABLED),
    VAL_AND_NAME(PF_SSE3_INSTRUCTIONS_AVAILABLE),
    VAL_AND_NAME(PF_COMPARE_EXCHANGE128),
    VAL_AND_NAME(PF_COMPARE64_EXCHANGE128),
    VAL_AND_NAME(PF_CHANNELS_ENABLED),
    VAL_AND_NAME(PF_XSAVE_ENABLED),
    VAL_AND_NAME(PF_SECOND_LEVEL_ADDRESS_TRANSLATION),
    VAL_AND_NAME(PF_VIRT_FIRMWARE_ENABLED),
};

现在你有一个(值,名称)对的数组,你只需循环。 ranged-for语法非常有效:

char buffer[1000];
for( auto f : features ) {
    wsprintfA(buffer, "%40s : %s\n",
                      f.name, IsProcessorFeaturePresent(f.val)? "true": "false");
    // write buffer to standard output or wherever you like
}