The Marshal attribute in C#

 

The Marshal attribute is used to describe the marshalling format for a field, method, or parameter.

 

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Field)]

public class MarshalAttribute : System.Attribute

{

        public MarshalAttribute(UnmanagedType type) { }

        public string Cookie; public Guid IID;

        public Type Marshaler;

        public UnmanagedType NativeType { get { } }

        public int Size;

        public UnmanagedType SubType;

}

 

 

The Marshal attribute has the following behaviors:

 

  • It can only be placed on field declarations, method declarations, and formal parameters.
  • It has a single positional parameter of type UnmanagedType.
  • It has five named parameters.
  • The Cookie parameter gives a cookie that should be passed to the marshaler.
  • The IID parameter gives the Guid for NativeType.Interface types.
  • The Marshaler parameter specifies a marshaling class.
  • The Size parameter describes the size of a fixed size array or string. (Issue: what value is returned for other types?)
  • The SubType parameter describes the subsidiary type for NativeType.Ptr and NativeType.FixedArray types.
  • It is a single-use attribute class.