Unions in VB.Net?

  • Thread starter Thread starter Joel
  • Start date Start date
J

Joel

Does anybody know how to get unions to work in VB.Net?
What I'm trying to do is have a structure of a variety of
types of fields, and then I need to pass the whole thing
as a string later on. So I tried (see below) to use
LayoutKind.Explicit with FieldOffset, where I first set
the offset 0 to a string and then laid down the rest of
my fields. But instead of working like a union, it lays
the fields down sequentially (they don't overlap each
other as expected). Anybody know how to do this?

Thanks,

Joel


<System.Runtime.InteropServices.StructLayout
(System.Runtime.InteropServices.LayoutKind.Explicit)>
Public Structure IPCInitReqUnion
<System.Runtime.InteropServices.FieldOffset(0)
Dim s As String <System.Runtime.InteropServices.FieldOffset(0)
Dim HEADER As MyHeaderClass
<System.Runtime.InteropServices.FieldOffset
(88)> Dim USERID As String
<System.Runtime.InteropServices.FieldOffset
(120)> Dim PASSWORD As String
<System.Runtime.InteropServices.FieldOffset
(152)> Dim LocalLogon As Short
<System.Runtime.InteropServices.FieldOffset
(154)> Dim FTPProcessName() As String
<System.Runtime.InteropServices.FieldOffset
(184)> Dim NodeCount As Short
End Structure
 
Does anybody know how to get unions to work in VB.Net?
What I'm trying to do is have a structure of a variety of
types of fields, and then I need to pass the whole thing
as a string later on. So I tried (see below) to use
LayoutKind.Explicit with FieldOffset, where I first set
the offset 0 to a string and then laid down the rest of
my fields. But instead of working like a union, it lays
the fields down sequentially (they don't overlap each
other as expected). Anybody know how to do this?

Thanks,

Joel


<System.Runtime.InteropServices.StructLayout
(System.Runtime.InteropServices.LayoutKind.Explicit)>
Public Structure IPCInitReqUnion
<System.Runtime.InteropServices.FieldOffset(0)
<System.Runtime.InteropServices.FieldOffset
(88)> Dim USERID As String
<System.Runtime.InteropServices.FieldOffset
(120)> Dim PASSWORD As String
<System.Runtime.InteropServices.FieldOffset
(152)> Dim LocalLogon As Short
<System.Runtime.InteropServices.FieldOffset
(154)> Dim FTPProcessName() As String
<System.Runtime.InteropServices.FieldOffset
(184)> Dim NodeCount As Short
End Structure

Joel,

If I understand what your trying to do, then you'll probably want to do
something like:

<StructLayout(LayoutKind.Sequential)> _
Public Structure IPCIReq
Dim Header As MyHeaderClass
Dim UserId As String
....
End Structure

<SturctLayout(LayoutKind.Explicit)> _
Public Structure IPCIReqUnion
<FieldOffset(0)> _
Dim s As String
<FieldOffset(0)> _
Dim ipr As IPCIReq
End Structure


If that isn't what your after, it would probably be helpful to see the
C/C++ declarations.
 
Back
Top