I have this C# code to get Processor ID but I'm not able to pass it to C++, I tried a lot but I really can't, I just started in C++ and I would like to be able to get the CPU ID with C++ like I used to get with C#
This is the code I have in C#:
public static string GetProcessorID()
{
string sProcessorID = "";
string sQuery = "SELECT ProcessorId FROM Win32_Processor";
ManagementObjectSearcher oManagementObjectSearcher = new ManagementObjectSearcher(sQuery);
ManagementObjectCollection oCollection = oManagementObjectSearcher.Get();
foreach (ManagementObject oManagementObject in oCollection)
{
sProcessorID = (string)oManagementObject["ProcessorId"];
}
return (sProcessorID);
}
If it is just the problem of sending the obtained ProcessorID of type string (managed code) to unmanaged code (c++), then you can try variety of option like using a COM interface or through some intermediate CLR CLI interface or using normal native dll writing marshalling code on your own.
Another way is to create a C# COM interface and accessing it from C++ to get the sProcessorID by calling your function GetProcessorID()
It's a little bit longer in C++! This is a full working example, note that if you change the query from
to
Then you can use the
QueryValue
function to query any property value.First you have to do all the initialization stuffs, they're packed into these two functions:
That done you can run your WQL query then you have to enumerate returned properties to find the one you need (you can make it simpler but in this way you can query multiple values). Note that if you query ALL values from Win32_Processor you'll get a lot of data. On some systems I saw it takes even 2 seconds to complete the query and to enumerate properties (so filter your query to include only data you need).
NOTE: this code is useful if you need to gather more informations than the simple ID of the CPU. It's a generic example to get one (or more) properties from a WQL query (as you did in C#). If you do not need to get any other information (and you do not think to use WMI in your C++ programs) then you may use the
__cpuid()
intrinsic as posted in a comment.__cpuid()
The
ProcessorId
property from WMI has following description:A good implementation should check more about strange cases but a naive implementation may be:
See also this post for a better C++-ish implementation.