ModuleBuilder.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 à l'aide du nom, du nom de la DLL dans laquelle la méthode a été définie, des attributs de la méthode, de la convention d'appel, du type de retour, des types de paramètres et des indicateurs PInvoke spécifiés.

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

Définit une méthode PInvoke à l'aide du nom, du nom de la DLL dans laquelle la méthode a été définie, des attributs de la méthode, de la convention d'appel, du type de retour, des types de paramètres et des indicateurs PInvoke spécifiés.

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

Définit une méthode PInvoke à l'aide du nom, du nom de la DLL dans laquelle la méthode a été définie, des attributs de la méthode, de la convention d'appel, du type de retour, des types de paramètres et des indicateurs PInvoke spécifiés.

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

MethodBuilder

Méthode PInvoke définie.

Exceptions

La méthode n'est pas statique ou le type conteneur est une interface.

  • ou -

La méthode est de type abstract.

  • ou -

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

name ou dllName est null.

Le type conteneur a été créé au préalable à l'aide de la méthode CreateType().

Exemples

l’exemple suivant illustre l’utilisation de la DefinePInvokeMethod méthode pour créer un MethodBuilder pour une méthode externe non managée, MessageBoxA , dans l’API Windows. L’exemple affiche une boîte de message avec les boutons Réessayer et Annuler et affiche la valeur de retour de la boîte de message.

Important

Pour obtenir une valeur de retour différente de zéro, vous devez ajouter MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de méthode après avoir créé le MethodBuilder , à l’aide des MethodBuilder.GetMethodImplementationFlags MethodBuilder.SetImplementationFlags méthodes et.

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

const int MB_RETRYCANCEL = 5;

void main()
{
   AssemblyName^ myAssemblyName = gcnew AssemblyName("TempAssembly");

   // Define a dynamic assembly in the current application domain.
   AssemblyBuilder^ myAssemblyBuilder = 
      AppDomain::CurrentDomain->DefineDynamicAssembly(
                  myAssemblyName, AssemblyBuilderAccess::Run);

   // Define a dynamic module in "TempAssembly" assembly.
   ModuleBuilder^ myModuleBuilder = 
      myAssemblyBuilder->DefineDynamicModule("TempModule");

   array<Type^>^ paramTypes = 
      { int::typeid, String::typeid, String::typeid, int::typeid };

   // Define a PInvoke method.
   MethodBuilder^ piMethodBuilder = myModuleBuilder->DefinePInvokeMethod(
      "MessageBoxA",
      "user32.dll",
      MethodAttributes::Public | MethodAttributes::Static | MethodAttributes::PinvokeImpl,
      CallingConventions::Standard,
      int::typeid,
      paramTypes,
      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.
   piMethodBuilder->SetImplementationFlags(
      piMethodBuilder->GetMethodImplementationFlags() | MethodImplAttributes::PreserveSig);

   // Create global methods.
   myModuleBuilder->CreateGlobalFunctions();

   // Arguments for calling the method.
   array<Object^>^ arguments = 
      { (Object^)(int) 0, "Hello World", "Title", MB_RETRYCANCEL };

   MethodInfo^ pinvokeMethod = myModuleBuilder->GetMethod("MessageBoxA");
   Console::WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...");
   Console::WriteLine("Message box returned: {0}", 
      pinvokeMethod->Invoke(nullptr, arguments));
};


/* This code example produces input similar to the following:

Testing module-level PInvoke method created with DefinePInvokeMethod...
Message box returned: 4
 */
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

namespace PInvoke
{
   public class Example
   {
      const int MB_RETRYCANCEL = 5;

      static void Main()
      {
         AssemblyName myAssemblyName = new AssemblyName("TempAssembly");

         // Define a dynamic assembly in the current application domain.
         AssemblyBuilder myAssemblyBuilder =
            AppDomain.CurrentDomain.DefineDynamicAssembly(
                        myAssemblyName, AssemblyBuilderAccess.Run);

         // Define a dynamic module in "TempAssembly" assembly.
         ModuleBuilder myModuleBuilder =
            myAssemblyBuilder.DefineDynamicModule("TempModule");

         Type[] paramTypes = { typeof(int), typeof(string), typeof(string), typeof(int) };

         // Define a PInvoke method.
         MethodBuilder piMethodBuilder = myModuleBuilder.DefinePInvokeMethod(
            "MessageBoxA",
            "user32.dll",
            MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
            CallingConventions.Standard,
            typeof(int),
            paramTypes,
            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.
         piMethodBuilder.SetImplementationFlags(
            piMethodBuilder.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);

         // Create global methods.
         myModuleBuilder.CreateGlobalFunctions();

         // Arguments for calling the method.
         Object[] arguments = { 0, "Hello World", "Title", MB_RETRYCANCEL };

         MethodInfo pinvokeMethod = myModuleBuilder.GetMethod("MessageBoxA");
         Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...");
         Console.WriteLine("Message box returned: {0}",
            pinvokeMethod.Invoke(null, arguments));
      }
   }
}

/* This code example produces input similar to the following:

Testing module-level PInvoke method created with DefinePInvokeMethod...
Message box returned: 4
 */
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices

Namespace PInvoke

   Public Class Example
   
      Const MB_RETRYCANCEL As Integer = 5

      Shared Sub Main()
      
         Dim myAssemblyName As New AssemblyName("TempAssembly")

         ' Define a dynamic assembly in the current application domain.
         Dim myAssemblyBuilder As AssemblyBuilder = _
            AppDomain.CurrentDomain.DefineDynamicAssembly( _
                        myAssemblyName, AssemblyBuilderAccess.Run)

         ' Define a dynamic module in "TempAssembly" assembly.
         Dim myModuleBuilder As ModuleBuilder = _
            myAssemblyBuilder.DefineDynamicModule("TempModule")

         Dim paramTypes() As Type = _
            { GetType(Integer), GetType(string), GetType(string), GetType(Integer) }

         ' Define a PInvoke method.
         Dim piMethodBuilder As MethodBuilder = myModuleBuilder.DefinePInvokeMethod( _
            "MessageBoxA", _
            "user32.dll", _
            MethodAttributes.Public Or MethodAttributes.Static Or MethodAttributes.PinvokeImpl, _
            CallingConventions.Standard, _
            GetType(Integer), _
            paramTypes, _
            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.
         piMethodBuilder.SetImplementationFlags( _
            piMethodBuilder.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig)

         ' Create global methods.
         myModuleBuilder.CreateGlobalFunctions()

         ' Arguments for calling the method.
         Dim arguments() As Object= { 0, "Hello World", "Title", MB_RETRYCANCEL }

         Dim pinvokeMethod As MethodInfo = _
            myModuleBuilder.GetMethod("MessageBoxA")
         Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...")
         Console.WriteLine("Message box returned: {0}", _
            pinvokeMethod.Invoke(Nothing, arguments))

      End Sub
   End Class
End Namespace

' This code example produces input similar to the following:
'
'Testing module-level PInvoke method created with DefinePInvokeMethod...
'Message box returned: 4

Remarques

Certains attributs d’importation de DLL (consultez la description de System. Runtime. InteropServices. DllImportAttribute) ne peuvent pas être spécifiés en tant qu’arguments pour cette méthode. Ces attributs doivent être définis en émettant un attribut personnalisé pour la méthode. Par exemple, l’attribut d’importation de DLL PreserveSig est défini en émettant un attribut personnalisé.

Notes

à compter de la .NET Framework 2,0 Service Pack 1, ce membre n’a plus besoin ReflectionPermission de l' ReflectionPermissionFlag.ReflectionEmit indicateur. (Voir problèmes de sécurité dans l’émission de réflexion.) pour utiliser cette fonctionnalité, votre application doit cibler le .NET Framework 3,5 ou une version ultérieure.

S’applique à

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

Définit une méthode PInvoke à l'aide du nom, du nom de la DLL dans laquelle la méthode a été définie, des attributs de la méthode, de la convention d'appel, du type de retour, des types de paramètres et des indicateurs PInvoke spécifiés.

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

MethodBuilder

Méthode PInvoke définie.

Exceptions

La méthode n'est pas statique, le type conteneur est une interface, la méthode est abstraite ou elle a été définie au préalable.

name ou dllName est null.

Le type conteneur a été créé au préalable à l'aide de la méthode CreateType().

Exemples

l’exemple suivant illustre l’utilisation de la DefinePInvokeMethod méthode pour créer un MethodBuilder pour une méthode externe non managée, MessageBoxA , dans l’API Windows. L’exemple affiche une boîte de message avec les boutons Réessayer et Annuler et affiche la valeur de retour de la boîte de message.

Important

Pour obtenir une valeur de retour différente de zéro, vous devez ajouter MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de méthode après avoir créé le MethodBuilder , à l’aide des MethodBuilder.GetMethodImplementationFlags MethodBuilder.SetImplementationFlags méthodes et.

Cet exemple utilise une surcharge différente de la DefinePInvokeMethod méthode, mais la technique est la même.

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

const int MB_RETRYCANCEL = 5;

void main()
{
   AssemblyName^ myAssemblyName = gcnew AssemblyName("TempAssembly");

   // Define a dynamic assembly in the current application domain.
   AssemblyBuilder^ myAssemblyBuilder = 
      AppDomain::CurrentDomain->DefineDynamicAssembly(
                  myAssemblyName, AssemblyBuilderAccess::Run);

   // Define a dynamic module in "TempAssembly" assembly.
   ModuleBuilder^ myModuleBuilder = 
      myAssemblyBuilder->DefineDynamicModule("TempModule");

   array<Type^>^ paramTypes = 
      { int::typeid, String::typeid, String::typeid, int::typeid };

   // Define a PInvoke method.
   MethodBuilder^ piMethodBuilder = myModuleBuilder->DefinePInvokeMethod(
      "MessageBoxA",
      "user32.dll",
      MethodAttributes::Public | MethodAttributes::Static | MethodAttributes::PinvokeImpl,
      CallingConventions::Standard,
      int::typeid,
      paramTypes,
      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.
   piMethodBuilder->SetImplementationFlags(
      piMethodBuilder->GetMethodImplementationFlags() | MethodImplAttributes::PreserveSig);

   // Create global methods.
   myModuleBuilder->CreateGlobalFunctions();

   // Arguments for calling the method.
   array<Object^>^ arguments = 
      { (Object^)(int) 0, "Hello World", "Title", MB_RETRYCANCEL };

   MethodInfo^ pinvokeMethod = myModuleBuilder->GetMethod("MessageBoxA");
   Console::WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...");
   Console::WriteLine("Message box returned: {0}", 
      pinvokeMethod->Invoke(nullptr, arguments));
};


/* This code example produces input similar to the following:

Testing module-level PInvoke method created with DefinePInvokeMethod...
Message box returned: 4
 */
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

namespace PInvoke
{
   public class Example
   {
      const int MB_RETRYCANCEL = 5;

      static void Main()
      {
         AssemblyName myAssemblyName = new AssemblyName("TempAssembly");

         // Define a dynamic assembly in the current application domain.
         AssemblyBuilder myAssemblyBuilder =
            AppDomain.CurrentDomain.DefineDynamicAssembly(
                        myAssemblyName, AssemblyBuilderAccess.Run);

         // Define a dynamic module in "TempAssembly" assembly.
         ModuleBuilder myModuleBuilder =
            myAssemblyBuilder.DefineDynamicModule("TempModule");

         Type[] paramTypes = { typeof(int), typeof(string), typeof(string), typeof(int) };

         // Define a PInvoke method.
         MethodBuilder piMethodBuilder = myModuleBuilder.DefinePInvokeMethod(
            "MessageBoxA",
            "user32.dll",
            MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
            CallingConventions.Standard,
            typeof(int),
            paramTypes,
            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.
         piMethodBuilder.SetImplementationFlags(
            piMethodBuilder.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);

         // Create global methods.
         myModuleBuilder.CreateGlobalFunctions();

         // Arguments for calling the method.
         Object[] arguments = { 0, "Hello World", "Title", MB_RETRYCANCEL };

         MethodInfo pinvokeMethod = myModuleBuilder.GetMethod("MessageBoxA");
         Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...");
         Console.WriteLine("Message box returned: {0}",
            pinvokeMethod.Invoke(null, arguments));
      }
   }
}

/* This code example produces input similar to the following:

Testing module-level PInvoke method created with DefinePInvokeMethod...
Message box returned: 4
 */
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices

Namespace PInvoke

   Public Class Example
   
      Const MB_RETRYCANCEL As Integer = 5

      Shared Sub Main()
      
         Dim myAssemblyName As New AssemblyName("TempAssembly")

         ' Define a dynamic assembly in the current application domain.
         Dim myAssemblyBuilder As AssemblyBuilder = _
            AppDomain.CurrentDomain.DefineDynamicAssembly( _
                        myAssemblyName, AssemblyBuilderAccess.Run)

         ' Define a dynamic module in "TempAssembly" assembly.
         Dim myModuleBuilder As ModuleBuilder = _
            myAssemblyBuilder.DefineDynamicModule("TempModule")

         Dim paramTypes() As Type = _
            { GetType(Integer), GetType(string), GetType(string), GetType(Integer) }

         ' Define a PInvoke method.
         Dim piMethodBuilder As MethodBuilder = myModuleBuilder.DefinePInvokeMethod( _
            "MessageBoxA", _
            "user32.dll", _
            MethodAttributes.Public Or MethodAttributes.Static Or MethodAttributes.PinvokeImpl, _
            CallingConventions.Standard, _
            GetType(Integer), _
            paramTypes, _
            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.
         piMethodBuilder.SetImplementationFlags( _
            piMethodBuilder.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig)

         ' Create global methods.
         myModuleBuilder.CreateGlobalFunctions()

         ' Arguments for calling the method.
         Dim arguments() As Object= { 0, "Hello World", "Title", MB_RETRYCANCEL }

         Dim pinvokeMethod As MethodInfo = _
            myModuleBuilder.GetMethod("MessageBoxA")
         Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...")
         Console.WriteLine("Message box returned: {0}", _
            pinvokeMethod.Invoke(Nothing, arguments))

      End Sub
   End Class
End Namespace

' This code example produces input similar to the following:
'
'Testing module-level PInvoke method created with DefinePInvokeMethod...
'Message box returned: 4

Remarques

Certains attributs d’importation de DLL (consultez la description de DllImportAttribute ) ne peuvent pas être spécifiés en tant qu’arguments pour cette méthode. Ces attributs doivent être définis en émettant un attribut personnalisé pour la méthode. Par exemple, l’attribut d’importation de DLL PreserveSig est défini en émettant un attribut personnalisé.

Notes

à compter de la .NET Framework 2,0 Service Pack 1, ce membre n’a plus besoin ReflectionPermission de l' ReflectionPermissionFlag.ReflectionEmit indicateur. (Voir problèmes de sécurité dans l’émission de réflexion.) pour utiliser cette fonctionnalité, votre application doit cibler le .NET Framework 3,5 ou une version ultérieure.

S’applique à