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);    } } 


C# in a Nutshell
C # in a Nutshell, Second Edition
ISBN: 0596005261
EAN: 2147483647
Year: 2005
Pages: 963

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net