Use Interop Code and Overlap Fields with the Union Construct in VB .NET
There are few idioms and constructs that Visual Basic .NET cannot touch. Although not especially good at pointers and addresses, VB .NET and C# enable a developer to emulate, contrive, or precisely reproduce almost everything else that even the most complex languages, such as C++, offer.
Implementing Union
To implement the example union, take the following steps:
- Add the Imports System.Runtime.InteropServices statement.
- Define a structure (Union, in this example).
- Apply the StructLayoutAttribute with LayoutKind.Explicit to the structure.
- Add two fields to the structure: an integer and a character.
- Apply the FieldOffsetAttribute to each of the fields, initializing the attribute with 0.
Listing 1 shows the results of this implementation.
Listing 1: A Structure Named Union That Implements the Union Construct
You are not limited to using integers and characters. You can use other types too, but you cannot mix reference types such as Object and String with value types like integer and char.<StructLayout(LayoutKind.Explicit)> _
Public Structure Union
<FieldOffset(0)> _
Public i As Integer
<FieldOffset(0)> _
Public ch As Char
End Structure
Listing 2: Using the Union Construct Demonstrated in Listing 1
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
Dim u As Union
u.i = 65
Console.WriteLine(u.ch)
Console.ReadLine()
End Sub
End Module
<StructLayout(LayoutKind.Explicit)> _
Public Structure Union
<FieldOffset(0)> _
Public i As Integer
<FieldOffset(0)> _
Public ch As Char
End Structure
The other values of LayoutKind are Auto, Explicit, and Sequential:
- Auto means that the layout is automatic and the type cannot be exported outside of managed code.
- Explicit means that you will define the layout of fields explicitly using the FieldOffsetAttribute. Explicit layout is used to position fields precisely, mapping managed types to unmanaged types.
- Sequential is used to lay out members in order of appearance. Sequentially laid out fields do not have to be contiguous.
Refer to Microsoft's integrated help for more examples of StructLayout, LayoutKind, and FieldOffset.
Union for VB .NET Programmers
VB .NET supports manufacturing even the advanced union idiom, which you previously found in languages like C and C++. Unions permit VB .NET programmers to overlap fields, which is useful when calling unmanaged code that returns a union.
No comments:
Post a Comment