开发者

C#: is there any standard compilation flag that allows me to detect if I'm compiling for x86 or x64?

开发者 https://www.devze.com 2023-01-22 08:52 出处:网络
I\'m using atomic operations on counters, and I care about performance. I know that on the 64-bit platform incrementing a long can be done in one shot, instead it requires two instructions in 32-bit p

I'm using atomic operations on counters, and I care about performance. I know that on the 64-bit platform incrementing a long can be done in one shot, instead it requires two instructions in 32-bit platforms

I have such a code fragment

#if X64
using COUNTER_TYPE = System.Int64;
#else
using COUNTER_TYPE = System.Int32;
#endif
开发者_如何转开发

But I define no X64 constant in my project's configuration. I wonder if there is a way to determine via #if statements if we are compiling for the x64 or not. When I implement a circular queue, I want to force its size up to 4 billions elements when running on x86, but I may appreciate unlocking its size to long.MaxValue when on x64. I know that on modern processors one or two instructions don't really care, but it's still my curiosity to know if I can detect the configuration via code without redefining an x64 profile with such constant specified.

Thank you.


One way to do this is to use System.IntPtr, which already abstracts the "bitness" of the assembly.

Note that by default, the C# compiler compiles for "anycpu" which means that the bitness of the assembly at runtime is determined by the bitness of the process into which it is loaded. For executable assemblies, this is x86 for 32 bit OS and x64 for 64 bit OS.

There are 3 equivalent ways to get the size of IntPtr:

// Use the static property
var size = IntPtr.Size;

// Use Marshal
var size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr));

// Use unsafe with sizeof
unsafe
{
    var size = sizeof(IntPtr);
}

I can't see any reason not to use the static property for all cases, since it is easiest.


No there is no such preprocessor flag available in part because C# doesn't really have a notion of compiling for different platforms. The command line option /platform doesn`t change the way the C# code is compiled at all but instead sets a flag on the resulting CLR binary restricting the type of processor the binary can run on.

In general though if you want to vary the size of a number value between 4 and 8 bytes based on a 32 and 64 bit platform, the bestn approach is to wrap the System.IntPtr type. This type will vary in this manner and your type can effectively use it as a backing store.

0

精彩评论

暂无评论...
验证码 换一张
取 消