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.

One such construct is the union. A union is like a structure, but it permits all its fields to share the same starting address. Consider a union with character and integer fields. The union structure would be 32 bits; that is, the union would be the size of the largest element. Assign a value to the char (say, 65) and the union would assign the integer the same value. When accessed through the integer field, it would return the value 65. When accessed through the character field, it would return the value A. Change one field and the other changes as well. Peter Norton did some famous work with unions that resulted in the now ubiquitous undelete application.

Although the most common reason to use a union probably is to map more than one field to the same memory address, you are not limited only to this use. This article demonstrates how to implement the union construct in VB .NET. You'll know when you need it.

Implementing Union

The union construct commonly is used to map more than one cardinal field to the same address. After all, cardinal fields (or numbers) overlap nicely. However, the most common application in .NET likely will be for interop—that is, using code that was written in something other than .NET. Whenever you use interop code, you use the System.Runtime.InteropServices namespace. It contains a lot of interesting code, including the Marshal class. For the example in this article, you add an Imports statement, but you should explore this namespace further on your own.

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

<StructLayout(LayoutKind.Explicit)> _
Public Structure Union
   <FieldOffset(0)> _
   Public i As Integer

   <FieldOffset(0)> _
   Public ch As Char
End Structure
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.

Listing 2 shows a simple console application that assigns the number 65 to the field i. When accessed through the field ch, the value is displayed as the character A.

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.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his new book UML DeMystified from McGraw-Hill/Osborne. Paul is an architect for Tri-State Hospital Supply Corporation. You may contact him for technology questions at pkimmel@softconcepts.com.

If you are interested in joining or sponsoring a .NET Users Group, check out www.glugnet.org.

Copyright © 2006 by Paul T. Kimmel. All Rights Reserved.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds