Casting explicitly laid out structures

Say I have this structure,

[StructLayout(LayoutKind.Explicit)] public struct Chapter4Time { [FieldOffset(0)] public UInt16 Unused; [FieldOffset(2)] public UInt16 TimeHigh; [FieldOffset(4)] public UInt16 TimeLow; [FieldOffset(6)] public UInt16 MicroSeconds; } 

and this structure.

 [StructLayout(LayoutKind.Explicit)] public struct IEEE_1588Time { [FieldOffset(0)] public UInt32 NanoSeconds; [FieldOffset(4)] public UInt32 Seconds; } 

How do I convert from one structure to another?

+4
source share
1 answer

Two options:

Unsafe code but explicit structure structure

(Note that although this is not dangerous for the C # compiler, some frameworks may still prohibit it - see Mark Gravel's comment.)

You can use a union type, which is another structure with two fields that are explicitly set in one place. Here is a complete example of using your structures:

 using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] public struct Chapter4Time { [FieldOffset(0)] public UInt16 Unused; [FieldOffset(2)] public UInt16 TimeHigh; [FieldOffset(4)] public UInt16 TimeLow; [FieldOffset(6)] public UInt16 MicroSeconds; } [StructLayout(LayoutKind.Explicit)] public struct IEEE_1588Time { [FieldOffset(0)] public UInt32 NanoSeconds; [FieldOffset(4)] public UInt32 Seconds; } [StructLayout(LayoutKind.Explicit)] public struct TimeUnion { [FieldOffset(0)] public Chapter4Time Chapter4Time; [FieldOffset(0)] public IEEE_1588Time IEEE_1588Time; } class Test { static void Main() { var ch4 = new Chapter4Time { TimeLow = 100, MicroSeconds = 50 }; var union = new TimeUnion { Chapter4Time = ch4 }; Console.WriteLine(union.IEEE_1588Time.Seconds); } } 

Insecure code, cast pointers

An alternative to the union type, if you can use unsafe code, is to indicate a pointer of type Chapter4Time* to IEEE_1588Time* :

 class Test { unsafe static void Main() { var ch4 = new Chapter4Time { TimeLow = 100, MicroSeconds = 50 }; var ieee1588 = *((IEEE_1588Time*) &ch4); Console.WriteLine(ieee1588.Seconds); } } 

Personally, I would avoid doing any of this, if at all possible, but if you really want to do this, these are probably the easiest approaches.

+5
source

Source: https://habr.com/ru/post/1491329/


All Articles