TypeBuilder.DefinePInvokeMethod Metod

Definition

Definierar en PInvoke metod.

Överlagringar

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

Definierar en PInvoke metod med namnet, namnet på den DLL där metoden definieras, metodens attribut, metodens anropande konvention, metodens returtyp, typen av parametrar för metoden och flaggorna PInvoke .

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

Definierar en PInvoke metod med namnet, namnet på den DLL där metoden definieras, namnet på startpunkten, metodens attribut, metodens anropskonvention, metodens returtyp, typerna av parametrarna för metoden och flaggorna PInvoke .

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

Definierar en PInvoke metod med namnet, namnet på den DLL där metoden definieras, namnet på startpunkten, metodens attribut, metodens anropande konvention, metodens returtyp, typerna av parametrarna för metoden, flaggorna PInvoke och anpassade modifierare för parametrarna och returtypen.

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

Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs

Definierar en PInvoke metod med namnet, namnet på den DLL där metoden definieras, metodens attribut, metodens anropande konvention, metodens returtyp, typen av parametrar för metoden och flaggorna 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);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")]
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);
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);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")>]
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
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

Parametrar

name
String

Namnet på PInvoke metoden. name kan inte innehålla inbäddade null-värden.

dllName
String

Namnet på den DLL där PInvoke metoden definieras.

attributes
MethodAttributes

Metodens attribut.

callingConvention
CallingConventions

Metodens anropskonvention.

returnType
Type

Metodens returtyp.

parameterTypes
Type[]

Typerna av metodens parametrar.

nativeCallConv
CallingConvention

Den interna anropskonventionen.

nativeCharSet
CharSet

Metodens interna teckenuppsättning.

Returer

Den definierade PInvoke metoden.

Attribut

Undantag

Metoden är inte statisk.

-eller-

Den överordnade typen är ett gränssnitt.

-eller-

Metoden är abstrakt.

-eller-

Metoden har definierats tidigare.

-eller-

Längden på name eller dllName är noll.

name eller dllName är null.

Den innehållande typen har skapats tidigare med hjälp av CreateType().

Exempel

I följande exempel visas hur du använder DefinePInvokeMethod metoden för att skapa en PInvoke metod och hur du lägger MethodImplAttributes.PreserveSig till flaggan i metodimplementeringsflaggorna när du har skapat MethodBuilder, med hjälp MethodBuilder.GetMethodImplementationFlags av metoderna och MethodBuilder.SetImplementationFlags .

Important

Om du vill få ett returvärde som inte är noll måste du lägga till MethodImplAttributes.PreserveSig flaggan.

Exemplet skapar en dynamisk sammansättning med en dynamisk modul och en enda typ, MyType, som innehåller PInvoke metoden. Metoden PInvoke representerar funktionen Win32 GetTickCount .

När exemplet körs körs PInvoke metoden. Den sparar även den dynamiska sammansättningen som PInvokeTest.dll. Du kan använda Ildasm.exe (IL Disassembler) för att undersöka klassen MyType och static (Shared i Visual Basic) PInvoke metod som den innehåller. Du kan kompilera ett Visual Basic- eller C#-program som använder metoden static MyType.GetTickCount genom att inkludera en referens till DLL-filen när du kör csc.exe eller vbc.exe, till exempel /r: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

Kommentarer

Vissa DLL-importattribut (se beskrivningen av DllImportAttribute) kan inte anges som argument för den här metoden. Till exempel måste DLL-importattributet MethodImplAttributes.PreserveSig läggas till när PInvoke metoden har skapats, om metoden returnerar ett värde. Exemplet visar hur du gör detta.

Gäller för

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

Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs

Definierar en PInvoke metod med namnet, namnet på den DLL där metoden definieras, namnet på startpunkten, metodens attribut, metodens anropskonvention, metodens returtyp, typerna av parametrarna för metoden och flaggorna 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);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")]
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);
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);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")>]
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
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

Parametrar

name
String

Namnet på PInvoke metoden. name kan inte innehålla inbäddade null-värden.

dllName
String

Namnet på den DLL där PInvoke metoden definieras.

entryName
String

Namnet på startpunkten i DLL:en.

attributes
MethodAttributes

Metodens attribut.

callingConvention
CallingConventions

Metodens anropskonvention.

returnType
Type

Metodens returtyp.

parameterTypes
Type[]

Typerna av metodens parametrar.

nativeCallConv
CallingConvention

Den interna anropskonventionen.

nativeCharSet
CharSet

Metodens interna teckenuppsättning.

Returer

Den definierade PInvoke metoden.

Attribut

Undantag

Metoden är inte statisk.

-eller-

Den överordnade typen är ett gränssnitt.

-eller-

Metoden är abstrakt.

-eller-

Metoden har definierats tidigare.

-eller-

Längden på name, dllNameeller entryName är noll.

name, dllName, eller entryName är null.

Den innehållande typen har skapats tidigare med hjälp av CreateType().

Exempel

I följande kodexempel visas hur du använder DefinePInvokeMethod metoden för att skapa en PInvoke metod och hur du lägger MethodImplAttributes.PreserveSig till flaggan i metodimplementeringsflaggorna när du har skapat MethodBuilder, med hjälp MethodBuilder.GetMethodImplementationFlags av metoderna och MethodBuilder.SetImplementationFlags .

Important

Om du vill få ett returvärde som inte är noll måste du lägga till MethodImplAttributes.PreserveSig flaggan.

Exemplet skapar en dynamisk sammansättning med en dynamisk modul och en enda typ, MyType, som innehåller PInvoke metoden. Metoden PInvoke representerar funktionen Win32 GetTickCount .

När exemplet körs körs PInvoke metoden. Den sparar även den dynamiska sammansättningen som PInvokeTest.dll. Du kan använda Ildasm.exe (IL Disassembler) för att undersöka klassen MyType och static (Shared i Visual Basic) PInvoke metod som den innehåller. Du kan kompilera ett Visual Basic- eller C#-program som använder metoden static MyType.GetTickCount genom att inkludera en referens till DLL-filen när du kör csc.exe eller vbc.exe, till exempel /r: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

Kommentarer

Vissa DLL-importattribut (se beskrivningen av DllImportAttribute) kan inte anges som argument för den här metoden. Till exempel måste DLL-importattributet MethodImplAttributes.PreserveSig läggas till när PInvoke metoden har skapats, om metoden returnerar ett värde. Exemplet visar hur du gör detta.

Gäller för

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

Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs
Källa:
TypeBuilder.cs

Definierar en PInvoke metod med namnet, namnet på den DLL där metoden definieras, namnet på startpunkten, metodens attribut, metodens anropande konvention, metodens returtyp, typerna av parametrarna för metoden, flaggorna PInvoke och anpassade modifierare för parametrarna och returtypen.

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);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")]
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);
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);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")>]
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
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

Parametrar

name
String

Namnet på PInvoke metoden. name kan inte innehålla inbäddade null-värden.

dllName
String

Namnet på den DLL där PInvoke metoden definieras.

entryName
String

Namnet på startpunkten i DLL:en.

attributes
MethodAttributes

Metodens attribut.

callingConvention
CallingConventions

Metodens anropskonvention.

returnType
Type

Metodens returtyp.

returnTypeRequiredCustomModifiers
Type[]

En matris med typer som representerar nödvändiga anpassade modifierare, till exempel IsConst, för metodens returtyp. Om returtypen inte har några nödvändiga anpassade modifierare anger du null.

returnTypeOptionalCustomModifiers
Type[]

En matris med typer som representerar valfria anpassade modifierare, till exempel IsConst, för metodens returtyp. Om returtypen inte har några valfria anpassade modifierare anger du null.

parameterTypes
Type[]

Typerna av metodens parametrar.

parameterTypeRequiredCustomModifiers
Type[][]

En matris med matriser av typer. Varje matris med typer representerar nödvändiga anpassade modifierare för motsvarande parameter, till exempel IsConst. Om en viss parameter inte har några nödvändiga anpassade modifierare anger du null i stället för en matris med typer. Om ingen av parametrarna har nödvändiga anpassade modifierare anger du null i stället för en matris med matriser.

parameterTypeOptionalCustomModifiers
Type[][]

En matris med matriser av typer. Varje matris med typer representerar valfria anpassade modifierare för motsvarande parameter, till exempel IsConst. Om en viss parameter inte har några valfria anpassade modifierare anger du null i stället för en matris med typer. Om ingen av parametrarna har valfria anpassade modifierare anger du null i stället för en matris med matriser.

nativeCallConv
CallingConvention

Den interna anropskonventionen.

nativeCharSet
CharSet

Metodens interna teckenuppsättning.

Returer

En MethodBuilder som representerar den definierade PInvoke metoden.

Attribut

Undantag

Metoden är inte statisk.

-eller-

Den överordnade typen är ett gränssnitt.

-eller-

Metoden är abstrakt.

-eller-

Metoden har definierats tidigare.

-eller-

Längden på name, dllNameeller entryName är noll.

-eller-

Storleken på parameterTypeRequiredCustomModifiers eller parameterTypeOptionalCustomModifiers är inte lika med storleken på parameterTypes.

name, dllName, eller entryName är null.

Typen skapades tidigare med .CreateType()

-eller-

För den aktuella dynamiska typen är IsGenericTypeegenskapen true , men egenskapen IsGenericTypeDefinition är false.

Exempel

I följande kodexempel visas hur du använder DefinePInvokeMethod metoden för att skapa en PInvoke metod och hur du lägger MethodImplAttributes.PreserveSig till flaggan i metodimplementeringsflaggorna när du har skapat MethodBuilder, med hjälp MethodBuilder.GetMethodImplementationFlags av metoderna och MethodBuilder.SetImplementationFlags .

Exemplet skapar en dynamisk sammansättning med en dynamisk modul och en enda typ, MyType, som innehåller PInvoke metoden. Metoden PInvoke representerar funktionen Win32 GetTickCount .

Important

Om du vill få ett returvärde som inte är noll måste du lägga till MethodImplAttributes.PreserveSig flaggan.

Note

I exemplet används en överlagring som inte anger anpassade modifierare. Om du vill ange anpassade modifierare ändrar du exempelkoden så att den använder den här metodens överlagring i stället.

När exemplet körs körs PInvoke metoden. Den sparar även den dynamiska sammansättningen som PInvokeTest.dll. Du kan använda Ildasm.exe (IL Disassembler) för att undersöka klassen MyType och static (Shared i Visual Basic) PInvoke metod som den innehåller. Du kan kompilera ett Visual Basic- eller C#-program som använder metoden static MyType.GetTickCount genom att inkludera en referens till DLL-filen när du kör csc.exe eller vbc.exe, till exempel /r: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

Kommentarer

Vissa DLL-importattribut (se beskrivningen av DllImportAttribute) kan inte anges som argument för den här metoden. Till exempel måste DLL-importattributet MethodImplAttributes.PreserveSig läggas till när PInvoke metoden har skapats, om metoden returnerar ett värde. Exemplet visar hur du gör detta.

Gäller för