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); } }
Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.