TypeBuilder.DefinePInvokeMethod Metódus

Definíció

Metódust PInvoke definiál.

Túlterhelések

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

Definiál egy metódust PInvoke a nevével, annak a DLL-nek a nevével, amelyben a metódus definiálva van, a metódus attribútumai, a metódus meghívási konvenciójának, a metódus visszatérési típusának, a metódus paramétereinek típusainak és a PInvoke jelzőknek a nevét.

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

Definiál egy metódust PInvoke a nevével, annak a DLL-nek a nevével, amelyben a metódus definiálva van, a belépési pont neve, a metódus attribútumai, a metódus hívási konvenciójának, a metódus visszatérési típusának, a metódus paramétereinek típusai és a PInvoke jelzők.

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

Definiál egy metódust PInvoke a nevével, annak a DLL-nek a nevével, amelyben a metódus definiálva van, a belépési pont neve, a metódus attribútumai, a metódus meghívási konvenciói, a metódus visszatérési típusa, a metódus paramétereinek típusai, a PInvoke paraméterek és a visszatérési típus egyéni módosítói.

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

Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs

Definiál egy metódust PInvoke a nevével, annak a DLL-nek a nevével, amelyben a metódus definiálva van, a metódus attribútumai, a metódus meghívási konvenciójának, a metódus visszatérési típusának, a metódus paramétereinek típusainak és a PInvoke jelzőknek a nevét.

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

Paraméterek

name
String

A metódus neve PInvoke . name nem tartalmazhat beágyazott null értékeket.

dllName
String

Annak a DLL-nek a neve, amelyben a PInvoke metódus definiálva van.

attributes
MethodAttributes

A metódus attribútumai.

callingConvention
CallingConventions

A metódus hívási konvenciója.

returnType
Type

A metódus visszatérési típusa.

parameterTypes
Type[]

A metódus paramétereinek típusai.

nativeCallConv
CallingConvention

A natív hívási konvenció.

nativeCharSet
CharSet

A metódus natív karakterkészlete.

Válaszok

A definiált PInvoke metódus.

Attribútumok

Kivételek

A metódus nem statikus.

-vagy-

A szülőtípus egy felület.

-vagy-

A módszer absztrakt.

-vagy-

A metódust korábban definiálták.

-vagy-

A hossz vagy namedllName nulla.

name vagy dllName az null.

A tartalmú típus korábban a következővel CreateType()lett létrehozva: .

Példák

Az alábbi példa bemutatja, hogyan hozhat létre metódust a DefinePInvokeMethod metódussal, és hogyan adhat hozzá PInvoke jelölőt a metódus implementálási jelzőihez a létrehozás után a MethodImplAttributes.PreserveSigmetódus és a MethodBuilderMethodBuilder.GetMethodImplementationFlags metódusok MethodBuilder.SetImplementationFlags használatával.

Important

Ha nem nulla visszatérési értéket szeretne lekérni, hozzá kell adnia a jelölőt MethodImplAttributes.PreserveSig .

A példa egy dinamikus szerelvényt hoz létre egy dinamikus modullal és egy olyan típussal, MyTypeamely tartalmazza a metódust PInvoke . A PInvoke metódus a Win32 GetTickCount függvényt jelöli.

A példa futtatásakor végrehajtja a metódust PInvoke . A dinamikus szerelvényt is menti PInvokeTest.dll. Az Ildasm.exe (IL Disassembler) segítségével megvizsgálhatja a MyType osztályt és a static (Shared Visual Basic) PInvoke metódust. A statikus MyType.GetTickCount metódust használó Visual Basic vagy C# programot úgy állíthatja össze, hogy csc.exe vagy vbc.exefuttatásakor a DLL-re mutató hivatkozást is beszed, például /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

Megjegyzések

Egyes DLL-importálási attribútumok (lásd a leírást DllImportAttribute) nem adhatók meg a metódus argumentumaiként. A DLL importálási attribútumot MethodImplAttributes.PreserveSig például a metódus létrehozása után PInvoke kell hozzáadni, ha a metódus értéket ad vissza. A példa bemutatja, hogyan teheti ezt meg.

A következőre érvényes:

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

Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs

Definiál egy metódust PInvoke a nevével, annak a DLL-nek a nevével, amelyben a metódus definiálva van, a belépési pont neve, a metódus attribútumai, a metódus hívási konvenciójának, a metódus visszatérési típusának, a metódus paramétereinek típusai és a PInvoke jelzők.

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

Paraméterek

name
String

A metódus neve PInvoke . name nem tartalmazhat beágyazott null értékeket.

dllName
String

Annak a DLL-nek a neve, amelyben a PInvoke metódus definiálva van.

entryName
String

A DLL belépési pontjának neve.

attributes
MethodAttributes

A metódus attribútumai.

callingConvention
CallingConventions

A metódus hívási konvenciója.

returnType
Type

A metódus visszatérési típusa.

parameterTypes
Type[]

A metódus paramétereinek típusai.

nativeCallConv
CallingConvention

A natív hívási konvenció.

nativeCharSet
CharSet

A metódus natív karakterkészlete.

Válaszok

A definiált PInvoke metódus.

Attribútumok

Kivételek

A metódus nem statikus.

-vagy-

A szülőtípus egy felület.

-vagy-

A módszer absztrakt.

-vagy-

A metódust korábban definiálták.

-vagy-

nameA hossz , dllNamevagy entryName nulla.

name, dllNamevagy entryName igen null.

A tartalmú típus korábban a következővel CreateType()lett létrehozva: .

Példák

Az alábbi példakód bemutatja, hogyan hozhat létre metódust a DefinePInvokeMethod metódussal, és hogyan adhat hozzá jelölőt a PInvoke metódus implementálási jelzőihez a MethodImplAttributes.PreserveSiglétrehozás után a metódus és a MethodBuilderMethodBuilder.GetMethodImplementationFlags metódusok MethodBuilder.SetImplementationFlags használatával.

Important

Ha nem nulla visszatérési értéket szeretne lekérni, hozzá kell adnia a jelölőt MethodImplAttributes.PreserveSig .

A példa egy dinamikus szerelvényt hoz létre egy dinamikus modullal és egy olyan típussal, MyTypeamely tartalmazza a metódust PInvoke . A PInvoke metódus a Win32 GetTickCount függvényt jelöli.

A példa futtatásakor végrehajtja a metódust PInvoke . A dinamikus szerelvényt is menti PInvokeTest.dll. Az Ildasm.exe (IL Disassembler) segítségével megvizsgálhatja a MyType osztályt és a static (Shared Visual Basic) PInvoke metódust. A statikus MyType.GetTickCount metódust használó Visual Basic vagy C# programot úgy állíthatja össze, hogy csc.exe vagy vbc.exefuttatásakor a DLL-re mutató hivatkozást is beszed, például /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

Megjegyzések

Egyes DLL-importálási attribútumok (lásd a leírást DllImportAttribute) nem adhatók meg a metódus argumentumaiként. A DLL importálási attribútumot MethodImplAttributes.PreserveSig például a metódus létrehozása után PInvoke kell hozzáadni, ha a metódus értéket ad vissza. A példa bemutatja, hogyan teheti ezt meg.

A következőre érvényes:

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

Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs
Forrás:
TypeBuilder.cs

Definiál egy metódust PInvoke a nevével, annak a DLL-nek a nevével, amelyben a metódus definiálva van, a belépési pont neve, a metódus attribútumai, a metódus meghívási konvenciói, a metódus visszatérési típusa, a metódus paramétereinek típusai, a PInvoke paraméterek és a visszatérési típus egyéni módosítói.

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

Paraméterek

name
String

A metódus neve PInvoke . name nem tartalmazhat beágyazott null értékeket.

dllName
String

Annak a DLL-nek a neve, amelyben a PInvoke metódus definiálva van.

entryName
String

A DLL belépési pontjának neve.

attributes
MethodAttributes

A metódus attribútumai.

callingConvention
CallingConventions

A metódus hívási konvenciója.

returnType
Type

A metódus visszatérési típusa.

returnTypeRequiredCustomModifiers
Type[]

A metódus visszatérési típusához a szükséges egyéni módosítókat képviselő típusok tömbje.IsConst Ha a visszatérési típus nem rendelkezik kötelező egyéni módosítókkal, adja meg a .null

returnTypeOptionalCustomModifiers
Type[]

Az opcionális egyéni módosítókat, például IsConsta metódus visszatérési típusát képviselő típusok tömbje. Ha a visszatérési típus nem tartalmaz opcionális egyéni módosítókat, adja meg a következőt null:

parameterTypes
Type[]

A metódus paramétereinek típusai.

parameterTypeRequiredCustomModifiers
Type[][]

Típustömbök tömbje. Minden típusok tömbje a megfelelő paraméterhez szükséges egyéni módosítókat jelöli, például IsConst. Ha egy adott paraméterhez nincs szükség egyéni módosítókra, adja meg null a típusok tömbje helyett. Ha egyik paraméter sem rendelkezik kötelező egyéni módosítókkal, tömbtömb helyett adja meg null .

parameterTypeOptionalCustomModifiers
Type[][]

Típustömbök tömbje. Minden típustömb a megfelelő paraméter opcionális egyéni módosítóit jelöli, például IsConst. Ha egy adott paraméter nem rendelkezik választható egyéni módosítókkal, adja meg null a típusok tömbje helyett. Ha egyik paraméter sem rendelkezik választható egyéni módosítókkal, tömbök tömbje helyett adja meg null .

nativeCallConv
CallingConvention

A natív hívási konvenció.

nativeCharSet
CharSet

A metódus natív karakterkészlete.

Válaszok

A MethodBuilder definiált PInvoke metódust jelképező.

Attribútumok

Kivételek

A metódus nem statikus.

-vagy-

A szülőtípus egy felület.

-vagy-

A módszer absztrakt.

-vagy-

A metódust korábban definiálták.

-vagy-

nameA hossz , dllNamevagy entryName nulla.

-vagy-

A méret vagy parameterTypeRequiredCustomModifiersparameterTypeOptionalCustomModifiers nem egyenlő a méretével parameterTypes.

name, dllNamevagy entryName igen null.

A típus korábban a következővel lett létrehozva CreateType(): .

-vagy-

Az aktuális dinamikus típus esetében a IsGenericType tulajdonság az true, de a IsGenericTypeDefinition tulajdonság az false.

Példák

Az alábbi példakód bemutatja, hogyan hozhat létre metódust a DefinePInvokeMethod metódussal, és hogyan adhat hozzá jelölőt a PInvoke metódus implementálási jelzőihez a MethodImplAttributes.PreserveSiglétrehozás után a metódus és a MethodBuilderMethodBuilder.GetMethodImplementationFlags metódusok MethodBuilder.SetImplementationFlags használatával.

A példa egy dinamikus szerelvényt hoz létre egy dinamikus modullal és egy olyan típussal, MyTypeamely tartalmazza a metódust PInvoke . A PInvoke metódus a Win32 GetTickCount függvényt jelöli.

Important

Ha nem nulla visszatérési értéket szeretne lekérni, hozzá kell adnia a jelölőt MethodImplAttributes.PreserveSig .

Note

A példa olyan túlterhelést használ, amely nem határoz meg egyéni módosítókat. Egyéni módosítók megadásához módosítsa a példakódot a metódus túlterhelésének használatára.

A példa futtatásakor végrehajtja a metódust PInvoke . A dinamikus szerelvényt is menti PInvokeTest.dll. Az Ildasm.exe (IL Disassembler) segítségével megvizsgálhatja a MyType osztályt és a static (Shared Visual Basic) PInvoke metódust. A statikus MyType.GetTickCount metódust használó Visual Basic vagy C# programot úgy állíthatja össze, hogy csc.exe vagy vbc.exefuttatásakor a DLL-re mutató hivatkozást is beszed, például /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

Megjegyzések

Egyes DLL-importálási attribútumok (lásd a leírást DllImportAttribute) nem adhatók meg a metódus argumentumaiként. A DLL importálási attribútumot MethodImplAttributes.PreserveSig például a metódus létrehozása után PInvoke kell hozzáadni, ha a metódus értéket ad vissza. A példa bemutatja, hogyan teheti ezt meg.

A következőre érvényes: