Marshaling Structures in the .NET Compact Framework
You can embed arrays and strings in structures for marshaling. You must use the MarshalAsAttribute attribute to specify how you want your embedded strings to be marshaled, otherwise an exception is thrown.
When marshaling a string to a wchar_t*,
you can specify either of the following attributes, which will marshal as a pointer to a Unicode string:
[MarshalAs(UnmanagedType.LPWStr)]
-or-
[MarshalAs(UnmanagedType.LPTStr)]
The following table shows structure definitions for marshaling arrays and strings from unmanaged to managed code. Note that some of these examples use the MarshalAsAttribute.
Data to marshal | Unmanaged structure (C++) | Managed structure (C#) |
---|---|---|
Array of integers |
|
|
Array of characters |
|
|
Array of characters to string |
|
|
Pointer to string |
|
|
Specifying a Structure Layout
You can specify how to lay out structures for the platform invoke marshaler with the StructLayoutAttribute attribute. The .NET Compact Framework supports all three LayoutKind enumeration values: Auto (default), Sequential, and Explicit.
In the .NET Compact Framework, Auto is equivalent to Sequential.
When an Explicit value is specified, a FieldOffsetAttribute attribute must be applied to every field. The byte values must be within the boundary of the type. For example, 2-byte integers must start on even addresses, 4-byte integers must start at addresses divisible by 4, and so on.
Note that the System.Runtime.InteropServices.StructLayoutAttribute.Pack field is not supported.