简体   繁体   中英

C# Preprocessor directives

In C++ we can do this:

struct {
#if defined (BIGENDIAN)
        uint32_t h;
        uint32_t l;
#else
        uint32_t l;
        uint32_t h;
#endif
    } dw;

Now, in C# not so simple. I have a method to test for BigEndian but to define the struct at compile time, how can we get the same effect in C#? I was thinking that I can have classes like "BoardBig" and "BoardLittle" and use a factory to get the class I need based off of the IsBigEndian check. And for _WIN64 checks, I can have classes like "Position_64" and "Position_32" something like that. Is this a good approach? Since C# cannot define statements like #define IsBigEndian 1 or what have ya, not sure what to do.

Update : And as other posters have pointed out (upvoted), this is not a solution for endianness in C#.

C# Conditional compilation directives

  #if BIGENDIAN
      uint32_t h;    
      uint32_t l;
  #else
      uint32_t l;
      uint32_t h;        
  #endif

BTW, you should avoid these if you can. Makes code harder to test.

There is conditional compilation in C#, but you can't use it to get different code depending on the endianess. For managed languages the endianess of the system is not known at compile time.

The compiler produces IL code, which can be executed both on big endian and little endian systems. It's the JIT compiler that takes care of turning the IL code into native machine code, and turn numeric literals into the correct format.

You can use BitConverter.IsLittleEndian to find out the endianess at runtime.

Since you cannot "memory-map" the C# structures to raw data, there is no real advantage is using preprocessor for this purpose. So while C# does have preprocessor features that can be used for other purposes, I don't think they will be valuable to you here.

Instead, just work with one preferred structure and bury the low-level bit-twiddling for the special cases. Here is an example of big-endian and little-endian handling for a structure:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM