Compartilhar via


Classe MarshalAsAttribute

 

Indica como realizar marshaling de dados entre código gerenciado e não gerenciado.

Namespace:   System.Runtime.InteropServices
Assembly:  mscorlib (em mscorlib.dll)

Hierarquia de Herança

System.Object
  System.Attribute
    System.Runtime.InteropServices.MarshalAsAttribute

Sintaxe

[AttributeUsageAttribute(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, 
    Inherited = false)]
[ComVisibleAttribute(true)]
public sealed class MarshalAsAttribute : Attribute
[AttributeUsageAttribute(AttributeTargets::Field | AttributeTargets::Parameter | AttributeTargets::ReturnValue, 
    Inherited = false)]
[ComVisibleAttribute(true)]
public ref class MarshalAsAttribute sealed : Attribute
[<Sealed>]
[<AttributeUsageAttribute(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue,
    Inherited = false)>]
[<ComVisibleAttribute(true)>]
type MarshalAsAttribute = 
    class
        inherit Attribute
    end
<AttributeUsageAttribute(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue,
    Inherited := False)>
<ComVisibleAttribute(True)>
Public NotInheritable Class MarshalAsAttribute
    Inherits Attribute

Construtores

Nome Descrição
System_CAPS_pubmethod MarshalAsAttribute(Int16)

Inicializa uma nova instância de MarshalAsAttribute classe com especificado UnmanagedType valor.

System_CAPS_pubmethod MarshalAsAttribute(UnmanagedType)

Inicializa uma nova instância da classe MarshalAsAttribute com o membro de enumeração UnmanagedType especificado.

Propriedades

Nome Descrição
System_CAPS_pubproperty TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.(Herdado de Attribute.)

System_CAPS_pubproperty Value

Obtém o UnmanagedType são empacotado como os dados de valor.

Métodos

Nome Descrição
System_CAPS_pubmethod Equals(Object)

Esta API dá suporte à infraestrutura produto e não se destina a ser usada diretamente do seu código. Retorna um valor que indica se essa instância é igual a um objeto especificado.(Herdado de Attribute.)

System_CAPS_pubmethod GetHashCode()

Retorna o código hash para essa instância.(Herdado de Attribute.)

System_CAPS_pubmethod GetType()

Obtém o Type da instância atual.(Herdado de Object.)

System_CAPS_pubmethod IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.(Herdado de Attribute.)

System_CAPS_pubmethod Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.(Herdado de Attribute.)

System_CAPS_pubmethod ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.(Herdado de Object.)

Campos

Nome Descrição
System_CAPS_pubfield ArraySubType

Especifica o tipo de elemento do UnmanagedType.LPArray não gerenciado ou UnmanagedType.ByValArray.

System_CAPS_pubfield IidParameterIndex

Especifica o índice de parâmetro de não gerenciado iid_is atributo usado por COM.

System_CAPS_pubfield MarshalCookie

Fornece informações adicionais para um empacotador personalizado.

System_CAPS_pubfield MarshalType

Especifica o nome totalmente qualificado de um marshaler personalizado.

System_CAPS_pubfield MarshalTypeRef

Implementa MarshalAsAttribute.MarshalType como um tipo.

System_CAPS_pubfield SafeArraySubType

Indica o tipo de elemento de UnmanagedType.SafeArray.

System_CAPS_pubfield SafeArrayUserDefinedSubType

Indica o tipo de elemento definido pelo usuário a UnmanagedType.SafeArray.

System_CAPS_pubfield SizeConst

Indica o número de elementos na matriz de comprimento fixo ou o número de caracteres (não em bytes) em uma cadeia de caracteres a importar.

System_CAPS_pubfield SizeParamIndex

Indica o parâmetro baseado em zero que contém a contagem de elementos da matriz, semelhante a size_is em COM.

Implementações Explícitas da Interface

Nome Descrição
System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.(Herdado de Attribute.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.(Herdado de Attribute.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).(Herdado de Attribute.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.(Herdado de Attribute.)

Comentários

You can apply this attribute to parameters, fields, or return values.

This attribute is optional, as each data type has a default marshaling behavior. This attribute is only necessary when a given type can be marshaled to multiple types. For example, you can marshal a string to unmanaged code as either a F:System.Runtime.InteropServices.UnmanagedType.LPStr, a F:System.Runtime.InteropServices.UnmanagedType.LPWStr, a F:System.Runtime.InteropServices.UnmanagedType.LPTStr, or a F:System.Runtime.InteropServices.UnmanagedType.BStr. By default, the common language runtime marshals a string parameter as a F:System.Runtime.InteropServices.UnmanagedType.BStr to COM methods. You can apply the T:System.Runtime.InteropServices.MarshalAsAttribute attribute to an individual field or parameter to cause that particular string to be marshaled as a F:System.Runtime.InteropServices.UnmanagedType.LPStr instead of a F:System.Runtime.InteropServices.UnmanagedType.BStr. The [<topic://cpgrfTypeLibraryExporterTlbexpexe>] passes your marshaling preferences to the common language runtime.

Some parameters and return values have different default marshaling behavior when used with COM interop or platform invoke. By default, the runtime marshals a string parameter (and fields in a value type) as a F:System.Runtime.InteropServices.UnmanagedType.LPStr to a platform invoke method or function. For additional information, see [<topic://cpcondefaultmarshalingbehavior>].

In most cases, the attribute simply identifies the format of the unmanaged data using the T:System.Runtime.InteropServices.UnmanagedType enumeration, as shown in the following C# signature:

public void SomeMethod([MarshalAs(UnmanagedType.LPStr)] String s)
Public Sub SomeMethod(<MarshalAs(UnmanagedType.LPStr)> s As String)

Some T:System.Runtime.InteropServices.UnmanagedType enumeration members require additional information. For example, additional information is needed when the T:System.Runtime.InteropServices.UnmanagedType is F:System.Runtime.InteropServices.UnmanagedType.LPArray. For a complete description of how to use this attribute with arrays, see [<topic://cpcondefaultmarshalingforarrays>].

The [<topic://cpgrfTypeLibraryImporterTlbimpexe>] also applies this attribute to parameters, fields, and return values to indicate that the data type in the input type library is not the default type for the corresponding managed data type. Tlbimp.exe always applies the T:System.Runtime.InteropServices.MarshalAsAttribute to T:System.String and T:System.Object types for clarity, regardless of the type specified in the input type library.

Observação

The T:System.Runtime.InteropServices.MarshalAsAttribute does not support marshaling of generic types.

Exemplos

The following example applies the T:System.Runtime.InteropServices.MarshalAsAttribute to a field, a method parameter, and a method return value in a managed type.

using System;
using System.Text;
using System.Runtime.InteropServices;


class Program
{

//Applied to a parameter.
  public void M1([MarshalAs(UnmanagedType.LPWStr)]String msg) {}


//Applied to a field within a class.
  class MsgText {
                [MarshalAs(UnmanagedType.LPWStr)]
                public String msg = "Hello World";
                }

//Applied to a return value.
[return: MarshalAs(UnmanagedType.LPWStr)]
    public String GetMessage()
    {
        return "Hello World";
    }


static void Main(string[] args)
    {  }
}
Imports System.Runtime.InteropServices

Module Module1

    Sub Main()

    End Sub

    'Applied to a parameter.
    Public Sub M1(<MarshalAsAttribute(UnmanagedType.LPWStr)> ByVal msg As String)
        msg = msg + "Goodbye"
    End Sub

    'Applied to a field within a class.
    Class MsgText
        <MarshalAsAttribute(UnmanagedType.LPWStr)> Public msg As String
    End Class

    'Applied to a a return value.
    Public Function M2() As <MarshalAsAttribute(UnmanagedType.LPWStr)> String
        Return "Hello World"
    End Function

End Module

The following example applies the T:System.Runtime.InteropServices.MarshalAsAttribute attribute to a property:

decimal _money;   

public decimal Money 
{
   [return: MarshalAs(UnmanagedType.Currency)]
   get { return this._money; }
   [param: MarshalAs(UnmanagedType.Currency)]
   set { this._money = value; }
}
Dim _money As Decimal   

Public Property Money As <MarshalAs(UnmanagedType.Currency)> Decimal 
   Get
      Return Me._money
   End Get
   Set(<MarshalAs(UnmanagedType.Currency)> value As Decimal)
      Me._money = value
   End Set   
End Property

Informações de Versão

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 1.1
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1

Acesso thread-safe

Quaisquer membros estáticos públicos ( Compartilhado no Visual Basic) desse tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Confira Também

UnmanagedType
Namespace System.Runtime.InteropServices
Tlbexp.exe (Exportador de Biblioteca de Tipos)
Tlbimp.exe (Importador de Biblioteca de Tipos)

Retornar ao início