[ Team LiB ] Previous Section Next Section

17.2 Marshaling Common Types

The CLR marshaler is a .NET facility that knows about the core types used by COM and the Windows API, and provides default translations to CLR types for you. The bool type, for instance, can be translated into a two-byte Windows BOOL type or a four-byte Boolean type. Using the MarshalAs attribute, you can override a default translation:

using System.Runtime.InteropServices;
static extern int Foo([MarshalAs(UnmanagedType.LPStr)]
                      string s);

In this case, the marshaler was told to use LPStr, so it will always use ANSI characters. Array classes and the StringBuilder class copy the marshaled value from an external function back to the managed value, as follows:

using System;
using System.Text;
using System.Runtime.InteropServices;
class Test {
  [DllImport("kernel32.dll")]
  static extern int GetWindowsDirectory(StringBuilder sb,
                                        int maxChars);
   static void Main( ) {
      StringBuilder s = new StringBuilder(256);
      GetWindowsDirectory(s, 256);
      Console.WriteLine(s);
   }
}
    [ Team LiB ] Previous Section Next Section