UnmanagedMarshal Classe

Definição

Cuidado

An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202

Cuidado

An alternate API is available: Emit the MarshalAs custom attribute instead.

Representa a classe que descreve como realizar marshaling de um campo de código gerenciado para código não gerenciado. Essa classe não pode ser herdada.

public ref class UnmanagedMarshal sealed
[System.Serializable]
public sealed class UnmanagedMarshal
[System.Serializable]
[System.Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class UnmanagedMarshal
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead.")]
public sealed class UnmanagedMarshal
[<System.Serializable>]
type UnmanagedMarshal = class
[<System.Serializable>]
[<System.Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type UnmanagedMarshal = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead.")>]
type UnmanagedMarshal = class
Public NotInheritable Class UnmanagedMarshal
Herança
UnmanagedMarshal
Atributos

Exemplos

O exemplo de código a seguir mostra o código de substituição para o tipo obsoleto UnmanagedMarshal . O exemplo emite um assembly de módulo único chamado EmitMarshalAs.dll, contendo um tipo chamado Sample. O tipo tem um método chamado Test, com um parâmetro do tipo String. O exemplo de código aplica-se ao MarshalAsAttribute UnmanagedType.BStr parâmetro.

Você pode usar o Ildasm.exe (Il Disassembler) para examinar o assembly emitido e observar que o parâmetro está marcado marshal(bstr).

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Runtime::InteropServices;

void main()
{
    AppDomain^ myDomain = AppDomain::CurrentDomain;
    AssemblyName^ myAsmName = gcnew AssemblyName("EmitMarshalAs");

    AssemblyBuilder^ myAssembly = 
        myDomain->DefineDynamicAssembly(myAsmName, 
            AssemblyBuilderAccess::RunAndSave);

    ModuleBuilder^ myModule = 
        myAssembly->DefineDynamicModule(myAsmName->Name, 
            myAsmName->Name + ".dll");
 
    TypeBuilder^ myType = 
        myModule->DefineType("Sample", TypeAttributes::Public);

    MethodBuilder^ myMethod = 
        myType->DefineMethod("Test", MethodAttributes::Public,
            nullptr, gcnew array<Type^> { String::typeid });


    // Get a parameter builder for the parameter that needs the 
    // attribute, using the HasFieldMarshal attribute. In this
    // example, the parameter is at position 0 and has the name
    // "arg".
    ParameterBuilder^ pb = 
        myMethod->DefineParameter(0, 
            ParameterAttributes::HasFieldMarshal, "arg");

    // Get the MarshalAsAttribute constructor that takes an
    // argument of type UnmanagedType.
    //
    //Type^ maattrType = MarshalAsAttribute::typeid;
    ConstructorInfo^ ci = 
        (MarshalAsAttribute::typeid)->GetConstructor(
            gcnew array<Type^> { UnmanagedType::typeid });

    // Create a CustomAttributeBuilder representing the attribute,
    // specifying the necessary unmanaged type. In this case, 
    // UnmanagedType.BStr is specified.
    //
    CustomAttributeBuilder^ cabuilder = 
        gcnew CustomAttributeBuilder(
            ci, gcnew array<Object^> { UnmanagedType::BStr });

    // Apply the attribute to the parameter.
    //
    pb->SetCustomAttribute(cabuilder);


    ILGenerator^ il = myMethod->GetILGenerator();
    il->Emit(OpCodes::Ret);

    Type^ finished = myType->CreateType();
    myAssembly->Save(myAsmName->Name + ".dll");
}
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

public class Example
{
    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName myAsmName = new AssemblyName("EmitMarshalAs");

        AssemblyBuilder myAssembly =
            myDomain.DefineDynamicAssembly(myAsmName,
                AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder myModule =
            myAssembly.DefineDynamicModule(myAsmName.Name,
               myAsmName.Name + ".dll");

        TypeBuilder myType =
            myModule.DefineType("Sample", TypeAttributes.Public);

        MethodBuilder myMethod =
            myType.DefineMethod("Test", MethodAttributes.Public,
                null, new Type[] { typeof(string) });

        // Get a parameter builder for the parameter that needs the
        // attribute, using the HasFieldMarshal attribute. In this
        // example, the parameter is at position 0 and has the name
        // "arg".
        ParameterBuilder pb =
            myMethod.DefineParameter(0,
               ParameterAttributes.HasFieldMarshal, "arg");

        // Get the MarshalAsAttribute constructor that takes an
        // argument of type UnmanagedType.
        //
        ConstructorInfo ci =
            typeof(MarshalAsAttribute).GetConstructor(
                new Type[] { typeof(UnmanagedType) });

        // Create a CustomAttributeBuilder representing the attribute,
        // specifying the necessary unmanaged type. In this case,
        // UnmanagedType.BStr is specified.
        //
        CustomAttributeBuilder cabuilder =
            new CustomAttributeBuilder(
                ci, new object[] { UnmanagedType.BStr });

        // Apply the attribute to the parameter.
        //
        pb.SetCustomAttribute(cabuilder);

        // Emit a dummy method body.
        ILGenerator il = myMethod.GetILGenerator();
        il.Emit(OpCodes.Ret);

        Type finished = myType.CreateType();
        myAssembly.Save(myAsmName.Name + ".dll");
    }
}
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices

Public Class Example

    Public Shared Sub Main()

        Dim myDomain As AppDomain = AppDomain.CurrentDomain
        Dim myAsmName As New AssemblyName("EmitMarshalAs")

        Dim myAssembly As AssemblyBuilder = _
            myDomain.DefineDynamicAssembly(myAsmName, _
                AssemblyBuilderAccess.RunAndSave)

        Dim myModule As ModuleBuilder = _
            myAssembly.DefineDynamicModule(myAsmName.Name, _
                myAsmName.Name & ".dll")

        Dim myType As TypeBuilder = _
            myModule.DefineType("Sample", TypeAttributes.Public)
        
        Dim myMethod As MethodBuilder = _
            myType.DefineMethod("Test", MethodAttributes.Public, _
                Nothing, new Type() { GetType(String) })


        ' Get a parameter builder for the parameter that needs the 
        ' attribute, using the HasFieldMarshal attribute. In this
        ' example, the parameter is at position 0 and has the name
        ' "arg".
        Dim pb As ParameterBuilder = _
            myMethod.DefineParameter(0, _
               ParameterAttributes.HasFieldMarshal, "arg")

        ' Get the MarshalAsAttribute constructor that takes an
        ' argument of type UnmanagedType.
        '
        Dim ciParameters() As Type = { GetType(UnmanagedType) }
        Dim ci As ConstructorInfo = _
            GetType(MarshalAsAttribute).GetConstructor(ciParameters)

        ' Create a CustomAttributeBuilder representing the attribute,
        ' specifying the necessary unmanaged type. In this case, 
        ' UnmanagedType.BStr is specified.
        '
        Dim ciArguments() As Object = { UnmanagedType.BStr }
        Dim cabuilder As New CustomAttributeBuilder(ci, ciArguments)

        ' Apply the attribute to the parameter.
        '
        pb.SetCustomAttribute(cabuilder)


        ' Emit a dummy method body.
        Dim il As ILGenerator = myMethod.GetILGenerator()
        il.Emit(OpCodes.Ret)

        myType.CreateType()
        myAssembly.Save(myAsmName.Name & ".dll")

    End Sub

End Class

Comentários

O exemplo de código mostra a solução alternativa para esse tipo obsoleto.

Marshaling é o processo de empacotamento e descompactação de parâmetros para que chamadas de procedimento remoto possam ocorrer. Durante o marshaling, um campo pode passar por uma conversão de formato quando o formato do tipo gerenciado for diferente do formato do tipo não gerenciado correspondente. Por exemplo, talvez você queira empacotar um String tipo como um BSTR não gerenciado. Algumas conversões de formato são tratadas automaticamente pelo runtime. Para substituir o comportamento padrão, você deve usar a UnmanagedMarshal classe para definir a conversão de formato.

Propriedades

BaseType

Obtém um tipo base não gerenciado. Esta propriedade é somente para leitura.

ElementCount

Obtém um elemento de número. Esta propriedade é somente para leitura.

GetUnmanagedType

Indica um tipo não gerenciado. Esta propriedade é somente para leitura.

IIDGuid

Obtém um GUID. Esta propriedade é somente para leitura.

Métodos

DefineByValArray(Int32)

Especifica uma matriz de comprimento fixo (ByValArray) para realizar marshaling para código não gerenciado.

DefineByValTStr(Int32)

Especifica uma cadeia de caracteres em um buffer de matriz fixo (ByValTStr) para realizar marshaling para código não gerenciado.

DefineLPArray(UnmanagedType)

Especifica um LPArray para realizar marshaling para código não gerenciado. O comprimento de um LPArray é determinado em runtime pelo tamanho da matriz real em que se realizou marshaling.

DefineSafeArray(UnmanagedType)

Especifica um SafeArray para realizar marshaling para código não gerenciado.

DefineUnmanagedMarshal(UnmanagedType)

Especifica um determinado tipo que realizará marshaling para código não gerenciado.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também