1

I am not sure if this is correct but, if I am not mistaken, a unions is a [StructLayout(LayoutKind.Explicit)] structure where 2 or more elements are on the same field offset.

So if I have this:

typedef union _FILE_SEGMENT_ELEMENT {
    PVOID64 Buffer;
    ULONGLONG Alignment;
}

would this be in C# as:

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Explicit)]
public struct FileSegmentElement
{
    [FieldOffset(0)]
    public IntPtr Buffer;
    [FieldOffset(0)]
    public ulong Alignment;
}

or is this incorrect?

Jason787
  • 11
  • 1
  • @pstrjds in there he has a struct with a union in it. Does that also apply to just unions like the example above? – Jason787 Sep 15 '18 at 11:47
  • Yes. If you look at the accepted answer you will see that the `union` is being encapsulated by using the explicit `FieldOffset`. Also, pay attention to the comments in the answer as this will only work for primitive types. – pstrjds Sep 15 '18 at 11:49
  • Also, you may want to take a read [here](https://social.msdn.microsoft.com/Forums/en-US/60150e7b-665a-49a2-8e2e-2097986142f3/c-equivalent-to-c-quotunionquot?forum=csharplanguage) and pay attention to the statement about "endianness". – pstrjds Sep 15 '18 at 11:52
  • I think the best would be to use StructLayout(LayoutKind.Sequential) instead for IntPtr and ulong. Have a look at this link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind?view=netframework-4.7.2#System_Runtime_InteropServices_LayoutKind_Sequential – Somdip Dey Sep 15 '18 at 11:55
  • @SomdipDey - This would not work in the case presented here because we are talking about a `union` in the `C` language. To map that in `C#` you have to use the explicit layout and then place them both at the same offset. – pstrjds Sep 15 '18 at 19:56

0 Answers0