TypeBuilder.DefinePInvokeMethod Metodo

Definizione

Definisce un metodo PInvoke.

Overload

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

Definisce un metodo PInvoke in base al nome, al nome della DLL in cui è definito il metodo, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi di parametri del metodo e ai flag PInvoke.

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

Definisce un metodo PInvoke in base al nome, al nome della DLL in cui è definito il metodo, al nome del punto di ingresso, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi di parametri del metodo e ai flag PInvoke.

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

Definisce un metodo PInvoke in base al nome, al nome della DLL in cui è definito il metodo, al nome del punto di ingresso, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi di parametri del metodo, ai flag PInvoke e ai modificatori personalizzati relativi ai parametri e al tipo restituito.

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

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

Definisce un metodo PInvoke in base al nome, al nome della DLL in cui è definito il metodo, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi di parametri del metodo e ai flag 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

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.

-oppure-

Il tipo padre è un'interfaccia.

-oppure-

Il metodo è di tipo abstract.

-oppure-

Il metodo è stato definito in precedenza.

-oppure-

La lunghezza di name o dllName è zero.

name o dllName è null.

Il tipo contenitore è stato creato in precedenza con CreateType().

Esempio

Nell'esempio seguente viene illustrato come usare il DefinePInvokeMethod metodo per creare un PInvoke metodo e come aggiungere il flag ai flag di implementazione del MethodImplAttributes.PreserveSig metodo dopo aver creato , MethodBuilderusando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .

Importante

Per ottenere un valore restituito diverso da zero, è necessario aggiungere il MethodImplAttributes.PreserveSig flag.

Nell'esempio viene creato un assembly dinamico con un modulo dinamico e un singolo tipo, che MyTypecontiene il PInvoke metodo . Il PInvoke metodo rappresenta la funzione Win32 GetTickCount .

Quando viene eseguito l'esempio, esegue il PInvoke metodo . Salva anche l'assembly dinamico come PInvokeTest.dll. È possibile usare il Ildasm.exe (IL Disassembler) per esaminare la classe e il MyTypestatic metodo (Shared in Visual Basic) PInvoke che contiene. È possibile compilare un programma Visual Basic o C# che usa il metodo statico MyType.GetTickCount includendo un riferimento alla DLL quando si esegue csc.exe o vbc.exe, ad esempio /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

Commenti

Alcuni attributi di importazione DLL (vedere la descrizione di DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Ad esempio, l'attributo MethodImplAttributes.PreserveSig di importazione DLL deve essere aggiunto dopo la creazione del metodo, se il PInvoke metodo restituisce un valore. L'esempio illustra come eseguire questa operazione.

Si applica a

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

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

Definisce un metodo PInvoke in base al nome, al nome della DLL in cui è definito il metodo, al nome del punto di ingresso, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi di parametri del metodo e ai flag 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

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 padre è un'interfaccia.

-oppure-

Il metodo è di tipo abstract.

-oppure-

Il metodo è stato definito in precedenza.

-oppure-

La lunghezza di name, dllName o entryName è zero.

name, dllName o entryName è null.

Il tipo contenitore è stato creato in precedenza con CreateType().

Esempio

Nell'esempio di codice seguente viene illustrato come usare il DefinePInvokeMethod metodo per creare un PInvoke metodo e come aggiungere il MethodImplAttributes.PreserveSig flag ai flag di implementazione del metodo dopo aver creato , MethodBuilderusando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .

Importante

Per ottenere un valore restituito diverso da zero, è necessario aggiungere il MethodImplAttributes.PreserveSig flag.

Nell'esempio viene creato un assembly dinamico con un modulo dinamico e un singolo tipo, che MyTypecontiene il PInvoke metodo . Il PInvoke metodo rappresenta la funzione Win32 GetTickCount .

Quando viene eseguito l'esempio, esegue il PInvoke metodo . Salva anche l'assembly dinamico come PInvokeTest.dll. È possibile usare il Ildasm.exe (IL Disassembler) per esaminare la classe e il MyTypestatic metodo (Shared in Visual Basic) PInvoke che contiene. È possibile compilare un programma Visual Basic o C# che usa il metodo statico MyType.GetTickCount includendo un riferimento alla DLL quando si esegue csc.exe o vbc.exe, ad esempio /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

Commenti

Alcuni attributi di importazione DLL (vedere la descrizione di DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Ad esempio, l'attributo MethodImplAttributes.PreserveSig di importazione DLL deve essere aggiunto dopo la creazione del metodo, se il PInvoke metodo restituisce un valore. L'esempio illustra come eseguire questa operazione.

Si applica a

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

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

Definisce un metodo PInvoke in base al nome, al nome della DLL in cui è definito il metodo, al nome del punto di ingresso, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi di parametri del metodo, ai flag PInvoke e ai modificatori personalizzati relativi ai parametri e al tipo restituito.

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

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.

returnTypeRequiredCustomModifiers
Type[]

Matrice di tipi che rappresenta i modificatori personalizzati obbligatori, come IsConst, per il tipo restituito del metodo. Se il tipo restituito non ha modificatori personalizzati obbligatori, specificare null.

returnTypeOptionalCustomModifiers
Type[]

Matrice di tipi che rappresenta i modificatori personalizzati facoltativi, come IsConst, per il tipo restituito del metodo. Se il tipo restituito non ha modificatori personalizzati facoltativi, specificare null.

parameterTypes
Type[]

Tipi dei parametri del metodo.

parameterTypeRequiredCustomModifiers
Type[][]

Matrice di matrici di tipi. Ogni matrice di tipi rappresenta i modificatori personalizzati obbligatori per il parametro corrispondente, come IsConst. Se un parametro particolare non ha modificatori personalizzati obbligatori, specificare null invece di una matrice di tipi. Se nessun parametro ha modificatori personalizzati obbligatori, specificare null invece di una matrice di matrici.

parameterTypeOptionalCustomModifiers
Type[][]

Matrice di matrici di tipi. Ogni matrice di tipi rappresenta i modificatori personalizzati facoltativi per il parametro corrispondente, come IsConst. Se un parametro particolare non ha modificatori personalizzati facoltativi, specificare null invece di una matrice di tipi. Se nessun parametro ha modificatori personalizzati facoltativi, specificare null invece di una matrice di matrici.

nativeCallConv
CallingConvention

Convenzione di chiamata nativa.

nativeCharSet
CharSet

Set di caratteri nativo del metodo.

Restituisce

Oggetto MethodBuilder che rappresenta il metodo PInvoke definito.

Eccezioni

Il metodo non è statico.

-oppure-

Il tipo padre è un'interfaccia.

-oppure-

Il metodo è di tipo abstract.

-oppure-

Il metodo è stato definito in precedenza.

-oppure-

La lunghezza di name, dllName o entryName è zero.

-oppure-

La dimensione di parameterTypeRequiredCustomModifiers o parameterTypeOptionalCustomModifiers non è uguale a quella di parameterTypes.

name, dllName o entryName è null.

Il tipo è stato creato in precedenza usando CreateType().

-oppure-

Per il tipo dinamico corrente, la proprietà IsGenericType è true ma la proprietà IsGenericTypeDefinition è false.

Esempio

Nell'esempio di codice seguente viene illustrato come usare il DefinePInvokeMethod metodo per creare un PInvoke metodo e come aggiungere il MethodImplAttributes.PreserveSig flag ai flag di implementazione del metodo dopo aver creato , MethodBuilderusando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .

Nell'esempio viene creato un assembly dinamico con un modulo dinamico e un singolo tipo, che MyTypecontiene il PInvoke metodo . Il PInvoke metodo rappresenta la funzione Win32 GetTickCount .

Importante

Per ottenere un valore restituito diverso da zero, è necessario aggiungere il MethodImplAttributes.PreserveSig flag.

Nota

L'esempio usa un overload che non specifica modificatori personalizzati. Per specificare modificatori personalizzati, modificare invece il codice di esempio per usare questo overload del metodo.

Quando viene eseguito l'esempio, esegue il PInvoke metodo . Salva anche l'assembly dinamico come PInvokeTest.dll. È possibile usare il Ildasm.exe (IL Disassembler) per esaminare la classe e il MyTypestatic metodo (Shared in Visual Basic) PInvoke che contiene. È possibile compilare un programma Visual Basic o C# che usa il metodo statico MyType.GetTickCount includendo un riferimento alla DLL quando si esegue csc.exe o vbc.exe, ad esempio /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

Commenti

Alcuni attributi di importazione DLL (vedere la descrizione di DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Ad esempio, l'attributo MethodImplAttributes.PreserveSig di importazione DLL deve essere aggiunto dopo la creazione del PInvoke metodo, se il metodo restituisce un valore. L'esempio mostra come eseguire questa operazione.

Nota

Per altre informazioni sui modificatori personalizzati, vedere ECMA C# e Common Language Infrastructure Standards e Standard ECMA-335 - Common Language Infrastructure (CLI).

Si applica a