Team LiB
Previous Section Next Section

Advanced Customizing of Structures

There are three ways to define a .NET structure:

Simulating Unions in .NET

Since .NET does not contain unions as a built-in feature, you are forced to use struct and modify it. A big limitation of this is that you cannot use reference types in the union. Here is an example:

[StructLayout(LayoutKind.Explicit]
public struct MyUnion
{
           public long MyLong;
           [FieldOffset(0)] public int MyInt;
           [FieldOffset(0)] public long MyLong;
           [FieldOffset(0)] public short MyShort;
}

Using the IntPtr Class

The IntPtr class allows you to store pointers in managed code. It is commonly used in scenarios where you are dealing with struct**, C-style arrays, by-reference value types that could be null, VARIANT s containing structures, and SAFEARRAY s containing VARIANT s containing structures. (The next section presents an example of passing an array of interface pointers.) The following example demonstrates using the IntPtr class.

Code Example: Using the IntPtr Class
Start example
using System;
using System.Runtime.InteropServices;

namespace Client.Chapter_10___ COM and .NET Interoperability
{
          public class TestClass
          {
                 [STAThread]
                 static void Main(string[] args)
                 {
                        IntPtr ptr = IntPtr.Zero;

                        ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)));
                        Marshal.FreeHGlobal(ptr);
                 }
          }
}
End example

Team LiB
Previous Section Next Section