Marshaling Structures in the .NET Compact Framework
[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]
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)]
Note
The only types of pointers that can be marshaled within a structure using MarshalAsAttribute is a string to a wchar_t*.
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. For more information on using this attribute in the .NET Compact Framework, see Using the MarshalAsAttribute Attribute.
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 StructLayoutAttribute.Pack field is not supported.