Compartilhar via


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

typedef struct _MyStruct
{
  int intArray[10]; 
} MyStruct;
struct MyStruct
{
  [MarshalAs(
    UnmanagedType.ByValArray, 
    SizeConst = 10)]
  int[] intArray;
}

Array of characters

typedef struct _MyStruct
{
  char charArray[10]; 
} MyStruct;
struct MyStruct
{
  [MarshalAs(
    UnmanagedType.ByValArray, 
    SizeConst = 10)]
  char[] charArray;
}

Array of characters to string

typedef struct _MyStruct
{
  char charArray[10]; 
} MyStruct;
struct MyStruct
{
  [MarshalAs(
    UnmanagedType.ByValTStr, 
    SizeConst = 10)]
  String str;
}

Pointer to string

typedef struct _MyStruct
{
  wchar_t *pStr; 
} MyStruct;
struct MyStruct
{
  [MarshalAs(
    UnmanagedType.LPWStr)]
  String str;
}

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.

See Also

Other Resources

Marshaling Support