Compartir a través de


Clase DllImportAttribute

 

Publicado: octubre de 2016

Indica que una biblioteca de vínculos dinámicos (DLL) no administrada expone el método con atributos como un punto de entrada estático.

Espacio de nombres:   System.Runtime.InteropServices
Ensamblado:  mscorlib (en mscorlib.dll)

Jerarquía de herencia

System.Object
  System.Attribute
    System.Runtime.InteropServices.DllImportAttribute

Sintaxis

[AttributeUsageAttribute(AttributeTargets.Method, Inherited = false)]
[ComVisibleAttribute(true)]
public sealed class DllImportAttribute : Attribute
[AttributeUsageAttribute(AttributeTargets::Method, Inherited = false)]
[ComVisibleAttribute(true)]
public ref class DllImportAttribute sealed : Attribute
[<Sealed>]
[<AttributeUsageAttribute(AttributeTargets.Method, Inherited = false)>]
[<ComVisibleAttribute(true)>]
type DllImportAttribute = 
    class
        inherit Attribute
    end
<AttributeUsageAttribute(AttributeTargets.Method, Inherited := False)>
<ComVisibleAttribute(True)>
Public NotInheritable Class DllImportAttribute
    Inherits Attribute

Constructores

Nombre Descripción
System_CAPS_pubmethod DllImportAttribute(String)

Inicializa una nueva instancia de la DllImportAttribute clase con el nombre de la DLL que contiene el método para importar.

Propiedades

Nombre Descripción
System_CAPS_pubproperty TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.(Heredado de Attribute).

System_CAPS_pubproperty Value

Obtiene el nombre del archivo DLL que contiene el punto de entrada.

Métodos

Nombre Descripción
System_CAPS_pubmethod Equals(Object)

Esta API admite la infraestructura producto y no está diseñada para usarse directamente desde el código. Devuelve un valor que indica si esta instancia es igual que un objeto especificado.(Heredado de Attribute).

System_CAPS_pubmethod GetHashCode()

Devuelve el código hash de esta instancia.(Heredado de Attribute).

System_CAPS_pubmethod GetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_pubmethod IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.(Heredado de Attribute).

System_CAPS_pubmethod Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.(Heredado de Attribute).

System_CAPS_pubmethod ToString()

Devuelve una cadena que representa el objeto actual.(Heredado de Object).

Campos

Nombre Descripción
System_CAPS_pubfield BestFitMapping

Habilita o deshabilita el comportamiento de asignación con ajuste perfecto al convertir caracteres Unicode en caracteres ANSI.

System_CAPS_pubfield CallingConvention

Indica la convención de llamada de un punto de entrada.

System_CAPS_pubfield CharSet

Indica cómo calcular las referencias de parámetros de cadena al método y controla la eliminación de nombre.

System_CAPS_pubfield EntryPoint

Indica el nombre u ordinal del punto de entrada DLL que se llame.

System_CAPS_pubfield ExactSpelling

Controles si el DllImportAttribute.CharSet campo hace que common language runtime buscar una DLL no administrada para nombres de punto de entrada distinto del especificado.

System_CAPS_pubfield PreserveSig

Indica si los métodos no administrados que tienen HRESULT o retval devolver valores se traducen directamente o si HRESULT o retval devolver valores se convierten automáticamente en excepciones.

System_CAPS_pubfield SetLastError

Indica si el destinatario llama el SetLastError función de la API de Win32 antes de volver del método con atributos.

System_CAPS_pubfield ThrowOnUnmappableChar

Habilita o deshabilita el inicio de una excepción cuando un carácter Unicode que se convierte en un carácter "?" caracteres.

Implementaciones de interfaz explícitas

Nombre Descripción
System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod _Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).(Heredado de Attribute).

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

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.(Heredado de Attribute).

Comentarios

You can apply this attribute to methods.

The T:System.Runtime.InteropServices.DllImportAttribute attribute provides the information needed to call a function exported from an unmanaged DLL. As a minimum requirement, you must supply the name of the DLL containing the entry point.

You apply this attribute directly to C# and C++ method definitions; however, the Visual Basic compiler emits this attribute when you use the Declare statement. For complex method definitions that include F:System.Runtime.InteropServices.DllImportAttribute.BestFitMapping, F:System.Runtime.InteropServices.DllImportAttribute.CallingConvention, F:System.Runtime.InteropServices.DllImportAttribute.ExactSpelling, F:System.Runtime.InteropServices.DllImportAttribute.PreserveSig, F:System.Runtime.InteropServices.DllImportAttribute.SetLastError, or F:System.Runtime.InteropServices.DllImportAttribute.ThrowOnUnmappableChar fields, you apply this attribute directly to Visual Basic method definitions.

Note   JScript does not support this attribute. You can use C# or Visual Basic wrapper classes to access unmanaged API methods from JScript programs.

For additional information about using the platform invoke service to access functions in unmanaged DLLs, see [<topic://cpconconsumingunmanageddllfunctions>].

Nota

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

Ejemplos

The following code example shows how to use the T:System.Runtime.InteropServices.DllImportAttribute attribute to import the Win32 MessageBox function. The code example then calls the imported method.

using System;
using System.Runtime.InteropServices;

class Example
{
    // Use DllImport to import the Win32 MessageBox function.
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

    static void Main()
    {
        // Call the MessageBox function using platform invoke.
        MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
    }
}
Imports System
Imports System.Runtime.InteropServices

Module Example

    ' Use DllImport to import the Win32 MessageBox function.
    <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _
    Function MessageBox(ByVal hwnd As IntPtr, ByVal t As String, ByVal caption As String, ByVal t2 As UInt32) As Integer
    End Function


    Sub Main()
        ' Call the MessageBox function using platform invoke.
        MessageBox(New IntPtr(0), "Hello World!", "Hello Dialog", 0)
    End Sub

End Module

Información de versión

Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 1.1
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

Seguridad para subprocesos

Cualquier miembro ( Compartido en Visual Basic) estático público de este tipo es seguro para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Ver también

SetLastError
ExactSpelling
PreserveSig
CallingConvention
Espacio de nombres System.Runtime.InteropServices

Volver al principio