TypeBuilder.DefinePInvokeMethod Méthode

Définition

Définit une méthode PInvoke.

Surcharges

DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)

Définit une méthode PInvoke en fonction de son nom, du nom de la DLL dans laquelle elle est définie, des attributs de la méthode, de sa convention d’appel, de son type de retour, des types de ses paramètres et des indicateurs PInvoke.

DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)

Définit une méthode PInvoke en fonction de son nom, du nom de la DLL dans laquelle elle est définie, du nom du point d’entrée, des attributs de la méthode, de sa convention d’appel, de son type de retour, des types de ses paramètres et des indicateurs PInvoke.

DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)

Définit une méthode PInvoke en fonction de son nom, du nom de la DLL dans laquelle elle est définie, du nom du point d’entrée, des attributs de la méthode, de sa convention d’appel, de son type de retour, des types de ses paramètres, des indicateurs PInvoke et des modificateurs personnalisés des paramètres et du type de retour.

DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)

Source:
TypeBuilder.cs
Source:
TypeBuilder.cs
Source:
TypeBuilder.cs

Définit une méthode PInvoke en fonction de son nom, du nom de la DLL dans laquelle elle est définie, des attributs de la méthode, de sa convention d’appel, de son type de retour, des types de ses paramètres et des indicateurs PInvoke.

public:
 System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
member this.DefinePInvokeMethod : string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder

Paramètres

name
String

Nom de la méthode PInvoke. name ne peut pas contenir des valeurs Null imbriquées.

dllName
String

Nom de la DLL dans laquelle la méthode PInvoke est définie.

attributes
MethodAttributes

Attributs de la méthode.

callingConvention
CallingConventions

Convention d’appel de la méthode.

returnType
Type

Type de retour de la méthode.

parameterTypes
Type[]

Types des paramètres de la méthode.

nativeCallConv
CallingConvention

Convention d’appel native.

nativeCharSet
CharSet

Jeu de caractères natif de la méthode.

Retours

Méthode PInvoke définie.

Exceptions

La méthode n’est pas statique.

- ou -

Le type parent est une interface.

- ou -

La méthode est de type abstract.

- ou -

La méthode a déjà été définie.

- ou -

La longueur de name ou dllName est de zéro.

name ou dllName est null.

Le type conteneur a déjà été créé à l’aide de CreateType().

Exemples

L’exemple suivant montre comment utiliser la DefinePInvokeMethod méthode pour créer une PInvoke méthode et comment ajouter l’indicateur MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de méthode après avoir créé le , à l’aide MethodBuilderdes MethodBuilder.GetMethodImplementationFlags méthodes et MethodBuilder.SetImplementationFlags .

Important

Pour obtenir une valeur de retour autre que zéro, vous devez ajouter l’indicateur MethodImplAttributes.PreserveSig .

L’exemple crée un assembly dynamique avec un module dynamique et un type unique, MyType, qui contient la PInvoke méthode . La PInvoke méthode représente la fonction Win32 GetTickCount .

Lorsque l’exemple est exécuté, il exécute la PInvoke méthode . Il enregistre également l’assembly dynamique en tant que PInvokeTest.dll. Vous pouvez utiliser le Ildasm.exe (désassembleur IL) pour examiner la MyType classe et la static méthode (Shared en Visual Basic) PInvoke qu’elle contient. Vous pouvez compiler un programme Visual Basic ou C# qui utilise la méthode statique MyType.GetTickCount en incluant une référence à la DLL lorsque vous exécutez csc.exe ou vbc.exe ; par exemple, /r:PInvokeTest.dll.

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

    void main()
    {
        // Create the AssemblyBuilder.
        AssemblyName^ asmName = gcnew AssemblyName("PInvokeTest");
        AssemblyBuilder^ dynamicAsm = AppDomain::CurrentDomain->DefineDynamicAssembly(
            asmName, 
            AssemblyBuilderAccess::RunAndSave
        );

        // Create the module.
        ModuleBuilder^ dynamicMod = 
            dynamicAsm->DefineDynamicModule(asmName->Name, asmName->Name + ".dll");

        // Create the TypeBuilder for the class that will contain the 
        // signature for the PInvoke call.
        TypeBuilder^ tb = dynamicMod->DefineType(
            "MyType", 
            TypeAttributes::Public | TypeAttributes::UnicodeClass
        );
    
        MethodBuilder^ mb = tb->DefinePInvokeMethod(
            "GetTickCount",
            "Kernel32.dll",
            MethodAttributes::Public | MethodAttributes::Static | MethodAttributes::PinvokeImpl,
            CallingConventions::Standard,
            int::typeid,
            Type::EmptyTypes,
            CallingConvention::Winapi,
            CharSet::Ansi);

        // Add PreserveSig to the method implementation flags. NOTE: If this line
        // is commented out, the return value will be zero when the method is
        // invoked.
        mb->SetImplementationFlags(
            mb->GetMethodImplementationFlags() | MethodImplAttributes::PreserveSig);

        // The PInvoke method does not have a method body. 

        // Create the class and test the method.
        Type^ t = tb->CreateType();

        MethodInfo^ mi = t->GetMethod("GetTickCount");
        Console::WriteLine("Testing PInvoke method...");
        Console::WriteLine("GetTickCount returned: {0}", mi->Invoke(nullptr, nullptr));

        // Produce the .dll file.
        Console::WriteLine("Saving: " + asmName->Name + ".dll");
        dynamicAsm->Save(asmName->Name + ".dll");
    };

/* This example produces output similar to the following:

Testing PInvoke method...
GetTickCount returned: 1314410994
Saving: PInvokeTest.dll
 */
using System;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

public class Example
{
    public static void Main()
    {
        // Create the AssemblyBuilder.
        AssemblyName asmName = new AssemblyName("PInvokeTest");
        AssemblyBuilder dynamicAsm = AppDomain.CurrentDomain.DefineDynamicAssembly(
            asmName,
            AssemblyBuilderAccess.RunAndSave
        );

        // Create the module.
        ModuleBuilder dynamicMod =
            dynamicAsm.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");

        // Create the TypeBuilder for the class that will contain the
        // signature for the PInvoke call.
        TypeBuilder tb = dynamicMod.DefineType(
            "MyType",
            TypeAttributes.Public | TypeAttributes.UnicodeClass
        );

        MethodBuilder mb = tb.DefinePInvokeMethod(
            "GetTickCount",
            "Kernel32.dll",
            MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
            CallingConventions.Standard,
            typeof(int),
            Type.EmptyTypes,
            CallingConvention.Winapi,
            CharSet.Ansi);

        // Add PreserveSig to the method implementation flags. NOTE: If this line
        // is commented out, the return value will be zero when the method is
        // invoked.
        mb.SetImplementationFlags(
            mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);

        // The PInvoke method does not have a method body.

        // Create the class and test the method.
        Type t = tb.CreateType();

        MethodInfo mi = t.GetMethod("GetTickCount");
        Console.WriteLine("Testing PInvoke method...");
        Console.WriteLine("GetTickCount returned: {0}", mi.Invoke(null, null));

        // Produce the .dll file.
        Console.WriteLine("Saving: " + asmName.Name + ".dll");
        dynamicAsm.Save(asmName.Name + ".dll");
    }
}

/* This example produces output similar to the following:

Testing PInvoke method...
GetTickCount returned: 1312576235
Saving: PInvokeTest.dll
 */
Imports System.Text
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices

Public Class Example
    
    Public Shared Sub Main() 
        
        ' Create the AssemblyBuilder.
        Dim asmName As New AssemblyName("PInvokeTest")
        Dim dynamicAsm As AssemblyBuilder = _
            AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, _
                AssemblyBuilderAccess.RunAndSave)
        
        ' Create the module.
        Dim dynamicMod As ModuleBuilder = _
            dynamicAsm.DefineDynamicModule(asmName.Name, asmName.Name & ".dll")
        
        ' Create the TypeBuilder for the class that will contain the 
        ' signature for the PInvoke call.
        Dim tb As TypeBuilder = dynamicMod.DefineType("MyType", _
            TypeAttributes.Public Or TypeAttributes.UnicodeClass)
        
        Dim mb As MethodBuilder = tb.DefinePInvokeMethod( _
            "GetTickCount", _
            "Kernel32.dll", _
            MethodAttributes.Public Or MethodAttributes.Static Or MethodAttributes.PinvokeImpl, _
            CallingConventions.Standard, _
            GetType(Integer), _
            Type.EmptyTypes, _
            CallingConvention.Winapi, _
            CharSet.Ansi)

        ' Add PreserveSig to the method implementation flags. NOTE: If this line
        ' is commented out, the return value will be zero when the method is
        ' invoked.
        mb.SetImplementationFlags( _
            mb.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig)
        
        ' The PInvoke method does not have a method body.
        
        ' Create the class and test the method.
        Dim t As Type = tb.CreateType()

        Dim mi As MethodInfo = t.GetMethod("GetTickCount")
        Console.WriteLine("Testing PInvoke method...")
        Console.WriteLine("GetTickCount returned: {0}", mi.Invoke(Nothing, Nothing))

        ' Produce the .dll file.
        Console.WriteLine("Saving: " & asmName.Name & ".dll")
        dynamicAsm.Save(asmName.Name & ".dll")
    
    End Sub  
End Class 

' This example produces output similar to the following:
'
'Testing PInvoke method...
'GetTickCount returned: 1313078714
'Saving: PInvokeTest.dll

Remarques

Certains attributs d’importation DLL (voir la description de DllImportAttribute) ne peuvent pas être spécifiés en tant qu’arguments de cette méthode. Par exemple, l’attribut MethodImplAttributes.PreserveSig d’importation DLL doit être ajouté après la création de la PInvoke méthode, si la méthode retourne une valeur. L’exemple montre comment procéder.

S’applique à

DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)

Source:
TypeBuilder.cs
Source:
TypeBuilder.cs
Source:
TypeBuilder.cs

Définit une méthode PInvoke en fonction de son nom, du nom de la DLL dans laquelle elle est définie, du nom du point d’entrée, des attributs de la méthode, de sa convention d’appel, de son type de retour, des types de ses paramètres et des indicateurs PInvoke.

public:
 System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::String ^ entryName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
member this.DefinePInvokeMethod : string * string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, entryName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder

Paramètres

name
String

Nom de la méthode PInvoke. name ne peut pas contenir des valeurs Null imbriquées.

dllName
String

Nom de la DLL dans laquelle la méthode PInvoke est définie.

entryName
String

Nom du point d’entrée dans la DLL.

attributes
MethodAttributes

Attributs de la méthode.

callingConvention
CallingConventions

Convention d’appel de la méthode.

returnType
Type

Type de retour de la méthode.

parameterTypes
Type[]

Types des paramètres de la méthode.

nativeCallConv
CallingConvention

Convention d’appel native.

nativeCharSet
CharSet

Jeu de caractères natif de la méthode.

Retours

Méthode PInvoke définie.

Exceptions

La méthode n’est pas statique.

- ou -

Le type parent est une interface.

- ou -

La méthode est de type abstract.

- ou -

La méthode a déjà été définie.

- ou -

La longueur de name, dllName ou entryName est égale à zéro.

name, dllName ou entryName est null.

Le type conteneur a déjà été créé à l’aide de CreateType().

Exemples

L’exemple de code suivant montre comment utiliser la DefinePInvokeMethod méthode pour créer une PInvoke méthode et comment ajouter l’indicateur MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de méthode après avoir créé le MethodBuilder, à l’aide des MethodBuilder.GetMethodImplementationFlags méthodes et MethodBuilder.SetImplementationFlags .

Important

Pour obtenir une valeur de retour autre que zéro, vous devez ajouter l’indicateur MethodImplAttributes.PreserveSig .

L’exemple crée un assembly dynamique avec un module dynamique et un type unique, MyType, qui contient la PInvoke méthode . La PInvoke méthode représente la fonction Win32 GetTickCount .

Lorsque l’exemple est exécuté, il exécute la PInvoke méthode . Il enregistre également l’assembly dynamique en tant que PInvokeTest.dll. Vous pouvez utiliser le Ildasm.exe (désassembleur IL) pour examiner la MyType classe et la static méthode (Shared en Visual Basic) PInvoke qu’elle contient. Vous pouvez compiler un programme Visual Basic ou C# qui utilise la méthode statique MyType.GetTickCount en incluant une référence à la DLL lorsque vous exécutez csc.exe ou vbc.exe ; par exemple, /r:PInvokeTest.dll.

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

    void main()
    {
        // Create the AssemblyBuilder.
        AssemblyName^ asmName = gcnew AssemblyName("PInvokeTest");
        AssemblyBuilder^ dynamicAsm = AppDomain::CurrentDomain->DefineDynamicAssembly(
            asmName, 
            AssemblyBuilderAccess::RunAndSave
        );

        // Create the module.
        ModuleBuilder^ dynamicMod = 
            dynamicAsm->DefineDynamicModule(asmName->Name, asmName->Name + ".dll");

        // Create the TypeBuilder for the class that will contain the 
        // signature for the PInvoke call.
        TypeBuilder^ tb = dynamicMod->DefineType(
            "MyType", 
            TypeAttributes::Public | TypeAttributes::UnicodeClass
        );
    
        MethodBuilder^ mb = tb->DefinePInvokeMethod(
            "GetTickCount",
            "Kernel32.dll",
            MethodAttributes::Public | MethodAttributes::Static | MethodAttributes::PinvokeImpl,
            CallingConventions::Standard,
            int::typeid,
            Type::EmptyTypes,
            CallingConvention::Winapi,
            CharSet::Ansi);

        // Add PreserveSig to the method implementation flags. NOTE: If this line
        // is commented out, the return value will be zero when the method is
        // invoked.
        mb->SetImplementationFlags(
            mb->GetMethodImplementationFlags() | MethodImplAttributes::PreserveSig);

        // The PInvoke method does not have a method body. 

        // Create the class and test the method.
        Type^ t = tb->CreateType();

        MethodInfo^ mi = t->GetMethod("GetTickCount");
        Console::WriteLine("Testing PInvoke method...");
        Console::WriteLine("GetTickCount returned: {0}", mi->Invoke(nullptr, nullptr));

        // Produce the .dll file.
        Console::WriteLine("Saving: " + asmName->Name + ".dll");
        dynamicAsm->Save(asmName->Name + ".dll");
    };

/* This example produces output similar to the following:

Testing PInvoke method...
GetTickCount returned: 1314410994
Saving: PInvokeTest.dll
 */
using System;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

public class Example
{
    public static void Main()
    {
        // Create the AssemblyBuilder.
        AssemblyName asmName = new AssemblyName("PInvokeTest");
        AssemblyBuilder dynamicAsm = AppDomain.CurrentDomain.DefineDynamicAssembly(
            asmName,
            AssemblyBuilderAccess.RunAndSave
        );

        // Create the module.
        ModuleBuilder dynamicMod =
            dynamicAsm.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");

        // Create the TypeBuilder for the class that will contain the
        // signature for the PInvoke call.
        TypeBuilder tb = dynamicMod.DefineType(
            "MyType",
            TypeAttributes.Public | TypeAttributes.UnicodeClass
        );

        MethodBuilder mb = tb.DefinePInvokeMethod(
            "GetTickCount",
            "Kernel32.dll",
            MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
            CallingConventions.Standard,
            typeof(int),
            Type.EmptyTypes,
            CallingConvention.Winapi,
            CharSet.Ansi);

        // Add PreserveSig to the method implementation flags. NOTE: If this line
        // is commented out, the return value will be zero when the method is
        // invoked.
        mb.SetImplementationFlags(
            mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);

        // The PInvoke method does not have a method body.

        // Create the class and test the method.
        Type t = tb.CreateType();

        MethodInfo mi = t.GetMethod("GetTickCount");
        Console.WriteLine("Testing PInvoke method...");
        Console.WriteLine("GetTickCount returned: {0}", mi.Invoke(null, null));

        // Produce the .dll file.
        Console.WriteLine("Saving: " + asmName.Name + ".dll");
        dynamicAsm.Save(asmName.Name + ".dll");
    }
}

/* This example produces output similar to the following:

Testing PInvoke method...
GetTickCount returned: 1312576235
Saving: PInvokeTest.dll
 */
Imports System.Text
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices

Public Class Example
    
    Public Shared Sub Main() 
        
        ' Create the AssemblyBuilder.
        Dim asmName As New AssemblyName("PInvokeTest")
        Dim dynamicAsm As AssemblyBuilder = _
            AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, _
                AssemblyBuilderAccess.RunAndSave)
        
        ' Create the module.
        Dim dynamicMod As ModuleBuilder = _
            dynamicAsm.DefineDynamicModule(asmName.Name, asmName.Name & ".dll")
        
        ' Create the TypeBuilder for the class that will contain the 
        ' signature for the PInvoke call.
        Dim tb As TypeBuilder = dynamicMod.DefineType("MyType", _
            TypeAttributes.Public Or TypeAttributes.UnicodeClass)
        
        Dim mb As MethodBuilder = tb.DefinePInvokeMethod( _
            "GetTickCount", _
            "Kernel32.dll", _
            MethodAttributes.Public Or MethodAttributes.Static Or MethodAttributes.PinvokeImpl, _
            CallingConventions.Standard, _
            GetType(Integer), _
            Type.EmptyTypes, _
            CallingConvention.Winapi, _
            CharSet.Ansi)

        ' Add PreserveSig to the method implementation flags. NOTE: If this line
        ' is commented out, the return value will be zero when the method is
        ' invoked.
        mb.SetImplementationFlags( _
            mb.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig)
        
        ' The PInvoke method does not have a method body.
        
        ' Create the class and test the method.
        Dim t As Type = tb.CreateType()

        Dim mi As MethodInfo = t.GetMethod("GetTickCount")
        Console.WriteLine("Testing PInvoke method...")
        Console.WriteLine("GetTickCount returned: {0}", mi.Invoke(Nothing, Nothing))

        ' Produce the .dll file.
        Console.WriteLine("Saving: " & asmName.Name & ".dll")
        dynamicAsm.Save(asmName.Name & ".dll")
    
    End Sub  
End Class 

' This example produces output similar to the following:
'
'Testing PInvoke method...
'GetTickCount returned: 1313078714
'Saving: PInvokeTest.dll

Remarques

Certains attributs d’importation DLL (voir la description de DllImportAttribute) ne peuvent pas être spécifiés en tant qu’arguments de cette méthode. Par exemple, l’attribut MethodImplAttributes.PreserveSig d’importation DLL doit être ajouté après la création de la PInvoke méthode, si la méthode retourne une valeur. L’exemple montre comment procéder.

S’applique à

DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)

Source:
TypeBuilder.cs
Source:
TypeBuilder.cs
Source:
TypeBuilder.cs

Définit une méthode PInvoke en fonction de son nom, du nom de la DLL dans laquelle elle est définie, du nom du point d’entrée, des attributs de la méthode, de sa convention d’appel, de son type de retour, des types de ses paramètres, des indicateurs PInvoke et des modificateurs personnalisés des paramètres et du type de retour.

public:
 System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::String ^ entryName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ returnTypeRequiredCustomModifiers, cli::array <Type ^> ^ returnTypeOptionalCustomModifiers, cli::array <Type ^> ^ parameterTypes, cli::array <cli::array <Type ^> ^> ^ parameterTypeRequiredCustomModifiers, cli::array <cli::array <Type ^> ^> ^ parameterTypeOptionalCustomModifiers, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
member this.DefinePInvokeMethod : string * string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type[] * Type[] * Type[][] * Type[][] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, entryName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, returnTypeRequiredCustomModifiers As Type(), returnTypeOptionalCustomModifiers As Type(), parameterTypes As Type(), parameterTypeRequiredCustomModifiers As Type()(), parameterTypeOptionalCustomModifiers As Type()(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder

Paramètres

name
String

Nom de la méthode PInvoke. name ne peut pas contenir des valeurs Null imbriquées.

dllName
String

Nom de la DLL dans laquelle la méthode PInvoke est définie.

entryName
String

Nom du point d’entrée dans la DLL.

attributes
MethodAttributes

Attributs de la méthode.

callingConvention
CallingConventions

Convention d’appel de la méthode.

returnType
Type

Type de retour de la méthode.

returnTypeRequiredCustomModifiers
Type[]

Tableau de types représentant les modificateurs personnalisés requis, tels qu’IsConst, pour le type de retour de la méthode. Si le type de retour ne possède pas de modificateur personnalisé requis, spécifiez null.

returnTypeOptionalCustomModifiers
Type[]

Tableau de types représentant les modificateurs personnalisés facultatifs, tels qu’IsConst, pour le type de retour de la méthode. Si le type de retour ne possède pas de modificateur personnalisé facultatif, spécifiez null.

parameterTypes
Type[]

Types des paramètres de la méthode.

parameterTypeRequiredCustomModifiers
Type[][]

Tableau de tableaux de types. Chaque tableau de types représente les modificateurs personnalisés obligatoires pour le paramètre correspondant, comme IsConst. Si un paramètre particulier ne possède pas de modificateurs personnalisés obligatoires, spécifiez null plutôt qu’un tableau de types. Si aucun paramètre ne possède de modificateur personnalisé requis, spécifiez null plutôt qu’un tableau de tableaux.

parameterTypeOptionalCustomModifiers
Type[][]

Tableau de tableaux de types. Chaque tableau de types représente les modificateurs personnalisés facultatifs pour le paramètre correspondant, comme IsConst. Si un paramètre particulier ne possède pas de modificateurs personnalisés facultatifs, spécifiez null plutôt qu’un tableau de types. Si aucun paramètre ne possède de modificateur personnalisé facultatif, spécifiez null plutôt qu’un tableau de tableaux.

nativeCallConv
CallingConvention

Convention d’appel native.

nativeCharSet
CharSet

Jeu de caractères natif de la méthode.

Retours

MethodBuilder représentant la méthode PInvoke définie.

Exceptions

La méthode n’est pas statique.

- ou -

Le type parent est une interface.

- ou -

La méthode est de type abstract.

- ou -

La méthode a déjà été définie.

- ou -

La longueur de name, dllName ou entryName est égale à zéro.

- ou -

La taille de parameterTypeRequiredCustomModifiers ou parameterTypeOptionalCustomModifiers n’est pas égale à la taille de parameterTypes.

name, dllName ou entryName est null.

Le type a déjà été créé en utilisant CreateType().

- ou -

Pour le type dynamique actuel, la propriété IsGenericType a la valeur true, mais la propriété IsGenericTypeDefinition a la valeur false.

Exemples

L’exemple de code suivant montre comment utiliser la DefinePInvokeMethod méthode pour créer une PInvoke méthode et comment ajouter l’indicateur MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de méthode après avoir créé le MethodBuilder, à l’aide des MethodBuilder.GetMethodImplementationFlags méthodes et MethodBuilder.SetImplementationFlags .

L’exemple crée un assembly dynamique avec un module dynamique et un type unique, MyType, qui contient la PInvoke méthode . La PInvoke méthode représente la fonction Win32 GetTickCount .

Important

Pour obtenir une valeur de retour autre que zéro, vous devez ajouter l’indicateur MethodImplAttributes.PreserveSig .

Notes

L’exemple utilise une surcharge qui ne spécifie pas de modificateurs personnalisés. Pour spécifier des modificateurs personnalisés, modifiez l’exemple de code pour utiliser cette surcharge de méthode à la place.

Lorsque l’exemple est exécuté, il exécute la PInvoke méthode . Il enregistre également l’assembly dynamique en tant que PInvokeTest.dll. Vous pouvez utiliser le Ildasm.exe (désassembleur IL) pour examiner la MyType classe et la static méthode (Shared en Visual Basic) PInvoke qu’elle contient. Vous pouvez compiler un programme Visual Basic ou C# qui utilise la méthode statique MyType.GetTickCount en incluant une référence à la DLL lorsque vous exécutez csc.exe ou vbc.exe ; par exemple, /r:PInvokeTest.dll.

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

    void main()
    {
        // Create the AssemblyBuilder.
        AssemblyName^ asmName = gcnew AssemblyName("PInvokeTest");
        AssemblyBuilder^ dynamicAsm = AppDomain::CurrentDomain->DefineDynamicAssembly(
            asmName, 
            AssemblyBuilderAccess::RunAndSave
        );

        // Create the module.
        ModuleBuilder^ dynamicMod = 
            dynamicAsm->DefineDynamicModule(asmName->Name, asmName->Name + ".dll");

        // Create the TypeBuilder for the class that will contain the 
        // signature for the PInvoke call.
        TypeBuilder^ tb = dynamicMod->DefineType(
            "MyType", 
            TypeAttributes::Public | TypeAttributes::UnicodeClass
        );
    
        MethodBuilder^ mb = tb->DefinePInvokeMethod(
            "GetTickCount",
            "Kernel32.dll",
            MethodAttributes::Public | MethodAttributes::Static | MethodAttributes::PinvokeImpl,
            CallingConventions::Standard,
            int::typeid,
            Type::EmptyTypes,
            CallingConvention::Winapi,
            CharSet::Ansi);

        // Add PreserveSig to the method implementation flags. NOTE: If this line
        // is commented out, the return value will be zero when the method is
        // invoked.
        mb->SetImplementationFlags(
            mb->GetMethodImplementationFlags() | MethodImplAttributes::PreserveSig);

        // The PInvoke method does not have a method body. 

        // Create the class and test the method.
        Type^ t = tb->CreateType();

        MethodInfo^ mi = t->GetMethod("GetTickCount");
        Console::WriteLine("Testing PInvoke method...");
        Console::WriteLine("GetTickCount returned: {0}", mi->Invoke(nullptr, nullptr));

        // Produce the .dll file.
        Console::WriteLine("Saving: " + asmName->Name + ".dll");
        dynamicAsm->Save(asmName->Name + ".dll");
    };

/* This example produces output similar to the following:

Testing PInvoke method...
GetTickCount returned: 1314410994
Saving: PInvokeTest.dll
 */
using System;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

public class Example
{
    public static void Main()
    {
        // Create the AssemblyBuilder.
        AssemblyName asmName = new AssemblyName("PInvokeTest");
        AssemblyBuilder dynamicAsm = AppDomain.CurrentDomain.DefineDynamicAssembly(
            asmName,
            AssemblyBuilderAccess.RunAndSave
        );

        // Create the module.
        ModuleBuilder dynamicMod =
            dynamicAsm.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");

        // Create the TypeBuilder for the class that will contain the
        // signature for the PInvoke call.
        TypeBuilder tb = dynamicMod.DefineType(
            "MyType",
            TypeAttributes.Public | TypeAttributes.UnicodeClass
        );

        MethodBuilder mb = tb.DefinePInvokeMethod(
            "GetTickCount",
            "Kernel32.dll",
            MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
            CallingConventions.Standard,
            typeof(int),
            Type.EmptyTypes,
            CallingConvention.Winapi,
            CharSet.Ansi);

        // Add PreserveSig to the method implementation flags. NOTE: If this line
        // is commented out, the return value will be zero when the method is
        // invoked.
        mb.SetImplementationFlags(
            mb.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);

        // The PInvoke method does not have a method body.

        // Create the class and test the method.
        Type t = tb.CreateType();

        MethodInfo mi = t.GetMethod("GetTickCount");
        Console.WriteLine("Testing PInvoke method...");
        Console.WriteLine("GetTickCount returned: {0}", mi.Invoke(null, null));

        // Produce the .dll file.
        Console.WriteLine("Saving: " + asmName.Name + ".dll");
        dynamicAsm.Save(asmName.Name + ".dll");
    }
}

/* This example produces output similar to the following:

Testing PInvoke method...
GetTickCount returned: 1312576235
Saving: PInvokeTest.dll
 */
Imports System.Text
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices

Public Class Example
    
    Public Shared Sub Main() 
        
        ' Create the AssemblyBuilder.
        Dim asmName As New AssemblyName("PInvokeTest")
        Dim dynamicAsm As AssemblyBuilder = _
            AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, _
                AssemblyBuilderAccess.RunAndSave)
        
        ' Create the module.
        Dim dynamicMod As ModuleBuilder = _
            dynamicAsm.DefineDynamicModule(asmName.Name, asmName.Name & ".dll")
        
        ' Create the TypeBuilder for the class that will contain the 
        ' signature for the PInvoke call.
        Dim tb As TypeBuilder = dynamicMod.DefineType("MyType", _
            TypeAttributes.Public Or TypeAttributes.UnicodeClass)
        
        Dim mb As MethodBuilder = tb.DefinePInvokeMethod( _
            "GetTickCount", _
            "Kernel32.dll", _
            MethodAttributes.Public Or MethodAttributes.Static Or MethodAttributes.PinvokeImpl, _
            CallingConventions.Standard, _
            GetType(Integer), _
            Type.EmptyTypes, _
            CallingConvention.Winapi, _
            CharSet.Ansi)

        ' Add PreserveSig to the method implementation flags. NOTE: If this line
        ' is commented out, the return value will be zero when the method is
        ' invoked.
        mb.SetImplementationFlags( _
            mb.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig)
        
        ' The PInvoke method does not have a method body.
        
        ' Create the class and test the method.
        Dim t As Type = tb.CreateType()

        Dim mi As MethodInfo = t.GetMethod("GetTickCount")
        Console.WriteLine("Testing PInvoke method...")
        Console.WriteLine("GetTickCount returned: {0}", mi.Invoke(Nothing, Nothing))

        ' Produce the .dll file.
        Console.WriteLine("Saving: " & asmName.Name & ".dll")
        dynamicAsm.Save(asmName.Name & ".dll")
    
    End Sub  
End Class 

' This example produces output similar to the following:
'
'Testing PInvoke method...
'GetTickCount returned: 1313078714
'Saving: PInvokeTest.dll

Remarques

Certains attributs d’importation DLL (voir la description de DllImportAttribute) ne peuvent pas être spécifiés en tant qu’arguments de cette méthode. Par exemple, l’attribut MethodImplAttributes.PreserveSig d’importation DLL doit être ajouté après la création de la PInvoke méthode, si la méthode retourne une valeur. L’exemple montre comment procéder.

Notes

Pour plus d’informations sur les modificateurs personnalisés, consultez C# ECMA et Common Language Infrastructure Standards et Standard ECMA-335 - Common Language Infrastructure (CLI).

S’applique à