开发者

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 c开发者_C百科an 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.


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:

  • Marshalling a big-endian byte collection into a struct in order to pull out values


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜