Search code examples
c#process64-bit

C# IntPtr and ProcessorAffinity - how to exceed 32 bits?


I have a computer with more than 31 cpu cores. I would like to assign a process to cpu cores beyond the 31st. My issue is that IntPtr resolves to 32 bit integer on this machine. It is a 64-bit machine running 64-bit operating system. This seems to defy what is stated by Microsoft here

The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.

Here is how I am constructing the IntPtr:

public static IntPtr GetCpuBinaryValue(int cpuIndex)
{
    // The IntPtr type is designed to be an integer whose size is platform - specific.
    // That is, an instance of this type is expected to be 32 - bits on 32 - bit hardware and operating systems,
    // and 64 - bits on 64 - bit hardware and operating systems.


    IntPtr ptr = new IntPtr(Convert.ToInt64(Math.Pow(2, cpuIndex)));
    return ptr;
}

And to continue the example, here is how I set the ProcessorAffinity:

using System.Diagnostics;
...
    // set which processor to run the process on
                process.ProcessorAffinity = GetCpuBinaryValue(coreIndex);
...

For example, I can pass in the value "0" and it will return an IntPtr (32-bit) with mask of 00000000 00000000 00000000 00000001

If I pass in "31" it will return 10000000 00000000 00000000 00000000

What I desire is for it to cast as 64 bit, for example if I pass in the value "32" it will return: 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000000

Is there a way to get around this issue? It is stubbornly stuck on 32-bit.


Solution

  • You're probably running in x86 or Any CPU. IntPtr is platform-specific, but it also depends on the process itself. If the Process is running in 64-bit mode, then pointers will be 64-bit, and if the process is running in 32-bit, then pointers will be 32-bit.

    If you switch to explicitly running as x64 (as described in How to: Configure Projects to Target Platforms), then the overflow exception goes away, and the correct value seems to be stored in the return value.