Export (0) Print
Expand All

Using the MarshalAsAttribute Attribute

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

You can use the MarshalAsAttribute attribute to customize marshaling behavior. For example, you can perform the following tasks:

  • Marshal arrays and strings in a structure.

  • Provide needed flexibility to support common COM interop scenarios.

  • Provide consistency in marshaling types through the platform invoke and vtable marshaler as compared to the IDispatch marshaler.

If using the MarshalAsAttribute for the unmanaged type fails, a NotSupportedException or a native exception may occur. If it fails, either use a known supported type, or remove the attribute and specify an IntPtr as the type. The Interop log reports information about marshaling errors.

The following table describes marshaling support for the values from the UnmanagedType enumeration.

Unmanaged Type

Types valid on

Supported in structures

Notes

BStr , TBStr

String

LPWStr, LPTStr

String

Yes

ANSI strings must be marshaled using an IntPtr and passed as an array of bytes.

LPStr

N/A

ANSI strings must be marshaled using an IntPtr and passed as an array of bytes.

IUnknown

Object

Yes

IDispatch

Object

Yes

ByValTStr

String

Yes

Supported in structures only.

ByValArray

Any array

Yes

SafeArray

Any array

Yes

VBByRefStr

String

Bool

Boolean ,

integer types

I1 , I2, I4

Integer types of appropriate length

U1 , U2, U4

Unsigned integer types of appropriate length

I8

N/A

U8

N/A

R4

4-byte real numbers

R8

8-byte real numbers

Struct

Object

Interface

Object

SysInt , SysUInt

Integer types of appropriate sign and length

AnsiBStr

N/A

ANSI strings must be marshaled using an IntPtr and passed as an array of bytes.

VariantBool

Boolean

FunctionPtr

N/A

AsAny

N/A

LPArray

N/A

LPStruct

N/A

Error

4 byte integers

Currency

Decimal

Show:
© 2014 Microsoft