Leggere in inglese

Condividi tramite


ModuleBuilder.DefinePInvokeMethod Metodo

Definizione

Definisce un metodo PInvoke.

Overload

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

Definisce un metodo PInvoke, con il nome, il nome del file DLL nel quale viene definito il metodo, gli attributi, la convenzione di chiamata, il tipo restituito, i tipi di parametri e i flag PInvoke del metodo specificati.

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

Definisce un metodo PInvoke, con il nome, il nome del file DLL nel quale viene definito il metodo, gli attributi, la convenzione di chiamata, il tipo restituito, i tipi di parametri e i flag PInvoke del metodo specificati.

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

Origine:
ModuleBuilder.cs
Origine:
ModuleBuilder.cs
Origine:
ModuleBuilder.cs

Definisce un metodo PInvoke, con il nome, il nome del file DLL nel quale viene definito il metodo, gli attributi, la convenzione di chiamata, il tipo restituito, i tipi di parametri e i flag PInvoke del metodo specificati.

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);

Parametri

name
String

Nome del metodo PInvoke. name non può contenere valori Null incorporati.

dllName
String

Nome della DLL in cui è definito il metodo PInvoke.

attributes
MethodAttributes

Attributi del metodo.

callingConvention
CallingConventions

Convenzione di chiamata del metodo.

returnType
Type

Tipo restituito del metodo.

parameterTypes
Type[]

Tipi dei parametri del metodo.

nativeCallConv
CallingConvention

Convenzione di chiamata nativa.

nativeCharSet
CharSet

Set di caratteri nativo del metodo.

Restituisce

Metodo PInvoke definito.

Eccezioni

Il metodo non è statico o il tipo che lo contiene è un'interfaccia.

-oppure-

Il metodo è di tipo abstract.

-oppure-

Il metodo è stato definito in precedenza.

name o dllName è null.

Il tipo che lo contiene è stato creato in precedenza utilizzando CreateType().

Esempio

Nell'esempio seguente viene illustrato l'uso del DefinePInvokeMethod metodo per creare un oggetto per un MethodBuilder metodo esterno non gestito, MessageBoxA, nell'API Windows. Nell'esempio viene visualizzata una finestra di messaggio con i pulsanti Riprova e Annulla e viene visualizzato il valore restituito dalla finestra di messaggio.

Importante

Per ottenere un valore restituito diverso da zero, è necessario aggiungere MethodImplAttributes.PreserveSig ai flag di implementazione del metodo dopo aver creato MethodBuilder, usando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .

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
 */

Commenti

Alcuni attributi di importazione DLL (vedere la descrizione di System.Runtime.InteropServices.DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Tali attributi devono essere impostati creando un attributo personalizzato per il metodo . Ad esempio, l'attributo PreserveSig di importazione DLL viene impostato creando un attributo personalizzato.

Nota

A partire da .NET Framework 2.0 Service Pack 1, questo membro non richiede ReflectionPermission più con il ReflectionPermissionFlag.ReflectionEmit flag . Vedere Problemi di sicurezza in Reflection Emit. Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.

Si applica a

.NET 10 e altre versioni
Prodotto Versioni
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.1

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

Origine:
ModuleBuilder.cs
Origine:
ModuleBuilder.cs
Origine:
ModuleBuilder.cs

Definisce un metodo PInvoke, con il nome, il nome del file DLL nel quale viene definito il metodo, gli attributi, la convenzione di chiamata, il tipo restituito, i tipi di parametri e i flag PInvoke del metodo specificati.

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);

Parametri

name
String

Nome del metodo PInvoke. name non può contenere valori Null incorporati.

dllName
String

Nome della DLL in cui è definito il metodo PInvoke.

entryName
String

Nome del punto di ingresso nella DLL.

attributes
MethodAttributes

Attributi del metodo.

callingConvention
CallingConventions

Convenzione di chiamata del metodo.

returnType
Type

Tipo restituito del metodo.

parameterTypes
Type[]

Tipi dei parametri del metodo.

nativeCallConv
CallingConvention

Convenzione di chiamata nativa.

nativeCharSet
CharSet

Set di caratteri nativo del metodo.

Restituisce

Metodo PInvoke definito.

Eccezioni

Il metodo non è statico oppure il tipo che lo contiene è un'interfaccia oppure il metodo è astratto oppure il metodo è stato definito in precedenza.

name o dllName è null.

Il tipo che lo contiene è stato creato in precedenza utilizzando CreateType().

Esempio

Nell'esempio seguente viene illustrato l'uso del DefinePInvokeMethod metodo per creare un oggetto per un MethodBuilder metodo esterno non gestito, MessageBoxA, nell'API Windows. Nell'esempio viene visualizzata una finestra di messaggio con i pulsanti Riprova e Annulla e viene visualizzato il valore restituito dalla finestra di messaggio.

Importante

Per ottenere un valore restituito diverso da zero, è necessario aggiungere MethodImplAttributes.PreserveSig ai flag di implementazione del metodo dopo aver creato MethodBuilder, usando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .

In questo esempio viene utilizzato un overload diverso del DefinePInvokeMethod metodo , ma la tecnica è la stessa.

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
 */

Commenti

Alcuni attributi di importazione DLL (vedere la descrizione di DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Tali attributi devono essere impostati creando un attributo personalizzato per il metodo . Ad esempio, l'attributo PreserveSig di importazione DLL viene impostato creando un attributo personalizzato.

Nota

A partire da .NET Framework 2.0 Service Pack 1, questo membro non richiede ReflectionPermission più con il ReflectionPermissionFlag.ReflectionEmit flag . Vedere Problemi di sicurezza in Reflection Emit. Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.

Si applica a

.NET 10 e altre versioni
Prodotto Versioni
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.1