TypeBuilder.DefinePInvokeMethod Metoda

Definicja

Definiuje metodę PInvoke .

Przeciążenia

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

Definiuje metodę PInvoke o nazwie, nazwę biblioteki DLL, w której zdefiniowano metodę, atrybuty metody, konwencję wywoływania metody, zwracany typ metody, typy parametrów metody i PInvoke flagi.

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

Definiuje metodę PInvoke o nazwie, nazwę biblioteki DLL, w której zdefiniowano metodę, nazwę punktu wejścia, atrybuty metody, konwencję wywoływania metody, typ zwracany metody, typy parametrów metody i PInvoke flagi.

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

Definiuje metodę PInvoke o nazwie, nazwę biblioteki DLL, w której zdefiniowano metodę, nazwę punktu wejścia, atrybuty metody, konwencję wywoływania metody, typ zwracany metody, typy parametrów metody, PInvoke flagi i modyfikatory niestandardowe dla parametrów i typu zwracanego.

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

Źródło:
TypeBuilder.cs
Źródło:
TypeBuilder.cs
Źródło:
TypeBuilder.cs

Definiuje metodę PInvoke o nazwie, nazwę biblioteki DLL, w której zdefiniowano metodę, atrybuty metody, konwencję wywoływania metody, zwracany typ metody, typy parametrów metody i PInvoke flagi.

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

Parametry

name
String

Nazwa PInvoke metody. name nie może zawierać osadzonych wartości null.

dllName
String

Nazwa biblioteki DLL, w której zdefiniowano metodę PInvoke .

attributes
MethodAttributes

Atrybuty metody .

callingConvention
CallingConventions

Konwencja wywoływania metody.

returnType
Type

Zwracany typ metody.

parameterTypes
Type[]

Typy parametrów metody.

nativeCallConv
CallingConvention

Natywna konwencja wywoływania.

nativeCharSet
CharSet

Natywny zestaw znaków metody.

Zwraca

Zdefiniowana PInvoke metoda.

Wyjątki

Metoda nie jest statyczna.

-lub-

Typ nadrzędny jest interfejsem.

-lub-

Metoda jest abstrakcyjna.

-lub-

Metoda została wcześniej zdefiniowana.

-lub-

Długość name lub dllName jest równa zero.

name lub dllName to null.

Typ zawierający został wcześniej utworzony przy użyciu polecenia CreateType().

Przykłady

W poniższym przykładzie pokazano, jak za pomocą DefinePInvokeMethod metody utworzyć metodę oraz jak dodać MethodImplAttributes.PreserveSig flagę PInvoke do flag implementacji metody po utworzeniu MethodBuildermetody przy użyciu MethodBuilder.GetMethodImplementationFlags metod i MethodBuilder.SetImplementationFlags .

Ważne

Aby uzyskać wartość zwracaną bez zera, należy dodać flagę MethodImplAttributes.PreserveSig .

W przykładzie tworzony jest zestaw dynamiczny z jednym modułem dynamicznym i pojedynczym typem zawierającym MyTypemetodę PInvoke . Metoda PInvoke reprezentuje funkcję Win32 GetTickCount .

Po uruchomieniu przykładu jest wykonywana PInvoke metoda . Zapisuje również zestaw dynamiczny jako PInvokeTest.dll. Można użyć Ildasm.exe (IL Dezasembler) do zbadania MyType klasy i static metody (Shared w Visual Basic), PInvoke która zawiera. Można skompilować program Visual Basic lub C#, który używa metody statycznej MyType.GetTickCount , dołączając odwołanie do biblioteki DLL podczas uruchamiania csc.exe lub vbc.exe, na przykład /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

Uwagi

Niektóre atrybuty importu bibliotek DLL (zobacz opis DllImportAttribute) nie można określić jako argumentów dla tej metody. Na przykład atrybut MethodImplAttributes.PreserveSig importu biblioteki DLL musi zostać dodany po utworzeniu PInvoke metody, jeśli metoda zwróci wartość. W przykładzie pokazano, jak to zrobić.

Dotyczy

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

Źródło:
TypeBuilder.cs
Źródło:
TypeBuilder.cs
Źródło:
TypeBuilder.cs

Definiuje metodę PInvoke o nazwie, nazwę biblioteki DLL, w której zdefiniowano metodę, nazwę punktu wejścia, atrybuty metody, konwencję wywoływania metody, typ zwracany metody, typy parametrów metody i PInvoke flagi.

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

Parametry

name
String

Nazwa PInvoke metody. name nie może zawierać osadzonych wartości null.

dllName
String

Nazwa biblioteki DLL, w której zdefiniowano metodę PInvoke .

entryName
String

Nazwa punktu wejścia w dll.

attributes
MethodAttributes

Atrybuty metody .

callingConvention
CallingConventions

Konwencja wywoływania metody.

returnType
Type

Zwracany typ metody.

parameterTypes
Type[]

Typy parametrów metody.

nativeCallConv
CallingConvention

Natywna konwencja wywoływania.

nativeCharSet
CharSet

Natywny zestaw znaków metody.

Zwraca

Zdefiniowana PInvoke metoda.

Wyjątki

Metoda nie jest statyczna.

-lub-

Typ nadrzędny jest interfejsem.

-lub-

Metoda jest abstrakcyjna.

-lub-

Metoda została wcześniej zdefiniowana.

-lub-

Długość parametru name, dllNamelub entryName ma wartość zero.

name, dllNamelub entryName to null.

Typ zawierający został wcześniej utworzony przy użyciu polecenia CreateType().

Przykłady

W poniższym przykładzie kodu pokazano, jak za pomocą DefinePInvokeMethod metody utworzyć metodę oraz jak dodać MethodImplAttributes.PreserveSig flagę PInvoke do flag implementacji metody po utworzeniu MethodBuilderelementu , przy użyciu MethodBuilder.GetMethodImplementationFlags metod iMethodBuilder.SetImplementationFlags.

Ważne

Aby uzyskać wartość zwracaną bez zera, należy dodać flagę MethodImplAttributes.PreserveSig .

W przykładzie tworzony jest zestaw dynamiczny z jednym modułem dynamicznym i pojedynczym typem zawierającym MyTypemetodę PInvoke . Metoda PInvoke reprezentuje funkcję Win32 GetTickCount .

Po uruchomieniu przykładu jest wykonywana PInvoke metoda . Zapisuje również zestaw dynamiczny jako PInvokeTest.dll. Można użyć Ildasm.exe (IL Dezasembler) do zbadania MyType klasy i static metody (Shared w Visual Basic), PInvoke która zawiera. Można skompilować program Visual Basic lub C#, który używa metody statycznej MyType.GetTickCount , dołączając odwołanie do biblioteki DLL podczas uruchamiania csc.exe lub vbc.exe, na przykład /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

Uwagi

Niektóre atrybuty importu bibliotek DLL (zobacz opis DllImportAttribute) nie można określić jako argumentów dla tej metody. Na przykład atrybut MethodImplAttributes.PreserveSig importu biblioteki DLL musi zostać dodany po utworzeniu PInvoke metody, jeśli metoda zwróci wartość. W przykładzie pokazano, jak to zrobić.

Dotyczy

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

Źródło:
TypeBuilder.cs
Źródło:
TypeBuilder.cs
Źródło:
TypeBuilder.cs

Definiuje metodę PInvoke o nazwie, nazwę biblioteki DLL, w której zdefiniowano metodę, nazwę punktu wejścia, atrybuty metody, konwencję wywoływania metody, typ zwracany metody, typy parametrów metody, PInvoke flagi i modyfikatory niestandardowe dla parametrów i typu zwracanego.

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

Parametry

name
String

Nazwa PInvoke metody. name nie może zawierać osadzonych wartości null.

dllName
String

Nazwa biblioteki DLL, w której zdefiniowano metodę PInvoke .

entryName
String

Nazwa punktu wejścia w dll.

attributes
MethodAttributes

Atrybuty metody .

callingConvention
CallingConventions

Konwencja wywoływania metody.

returnType
Type

Zwracany typ metody.

returnTypeRequiredCustomModifiers
Type[]

Tablica typów reprezentujących wymagane modyfikatory niestandardowe, takie jak IsConst, dla zwracanego typu metody. Jeśli typ zwracany nie ma wymaganych modyfikatorów niestandardowych, określ nullwartość .

returnTypeOptionalCustomModifiers
Type[]

Tablica typów reprezentujących opcjonalne modyfikatory niestandardowe, takie jak IsConst, dla zwracanego typu metody. Jeśli typ zwracany nie ma opcjonalnych modyfikatorów niestandardowych, określ nullwartość .

parameterTypes
Type[]

Typy parametrów metody.

parameterTypeRequiredCustomModifiers
Type[][]

Tablica tablic typów. Każda tablica typów reprezentuje wymagane modyfikatory niestandardowe dla odpowiedniego parametru, na przykład IsConst. Jeśli określony parametr nie ma wymaganych modyfikatorów niestandardowych, określ null zamiast tablicy typów. Jeśli żaden z parametrów nie ma wymaganych modyfikatorów niestandardowych, określ null zamiast tablicy tablic.

parameterTypeOptionalCustomModifiers
Type[][]

Tablica tablic typów. Każda tablica typów reprezentuje opcjonalne modyfikatory niestandardowe dla odpowiedniego parametru, na przykład IsConst. Jeśli określony parametr nie ma opcjonalnych modyfikatorów niestandardowych, określ null zamiast tablicy typów. Jeśli żaden z parametrów nie ma opcjonalnych modyfikatorów niestandardowych, określ null zamiast tablicy tablic.

nativeCallConv
CallingConvention

Natywna konwencja wywoływania.

nativeCharSet
CharSet

Natywny zestaw znaków metody.

Zwraca

Reprezentująca MethodBuilder zdefiniowaną PInvoke metodę.

Wyjątki

Metoda nie jest statyczna.

-lub-

Typ nadrzędny jest interfejsem.

-lub-

Metoda jest abstrakcyjna.

-lub-

Metoda została wcześniej zdefiniowana.

-lub-

Długość parametru name, dllNamelub entryName ma wartość zero.

-lub-

Rozmiar parameterTypeRequiredCustomModifiers lub parameterTypeOptionalCustomModifiers nie jest równy rozmiarowi elementu parameterTypes.

name, dllNamelub entryName to null.

Typ został wcześniej utworzony przy użyciu polecenia CreateType().

-lub-

Dla bieżącego typu IsGenericType dynamicznego właściwość to true, ale IsGenericTypeDefinition właściwość to false.

Przykłady

W poniższym przykładzie kodu pokazano, jak za pomocą DefinePInvokeMethod metody utworzyć metodę oraz jak dodać MethodImplAttributes.PreserveSig flagę PInvoke do flag implementacji metody po utworzeniu MethodBuilderelementu , przy użyciu MethodBuilder.GetMethodImplementationFlags metod iMethodBuilder.SetImplementationFlags.

W przykładzie tworzony jest zestaw dynamiczny z jednym modułem dynamicznym i pojedynczym typem zawierającym MyTypemetodę PInvoke . Metoda PInvoke reprezentuje funkcję Win32 GetTickCount .

Ważne

Aby uzyskać wartość zwracaną bez zera, należy dodać flagę MethodImplAttributes.PreserveSig .

Uwaga

W przykładzie użyto przeciążenia, które nie określa modyfikatorów niestandardowych. Aby określić modyfikatory niestandardowe, zmień przykładowy kod, aby zamiast tego użyć tego przeciążenia metody.

Po uruchomieniu przykładu jest wykonywana PInvoke metoda . Zapisuje również zestaw dynamiczny jako PInvokeTest.dll. Można użyć Ildasm.exe (IL Dezasembler) do zbadania MyType klasy i static metody (Shared w Visual Basic), PInvoke która zawiera. Można skompilować program Visual Basic lub C#, który używa metody statycznej MyType.GetTickCount , dołączając odwołanie do biblioteki DLL podczas uruchamiania csc.exe lub vbc.exe, na przykład /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

Uwagi

Niektóre atrybuty importu bibliotek DLL (zobacz opis DllImportAttribute) nie można określić jako argumentów dla tej metody. Na przykład atrybut MethodImplAttributes.PreserveSig importu biblioteki DLL musi zostać dodany po utworzeniu PInvoke metody, jeśli metoda zwróci wartość. W przykładzie pokazano, jak to zrobić.

Uwaga

Aby uzyskać więcej informacji na temat modyfikatorów niestandardowych, zobacz ECMA C# i Common Language Infrastructure Standards andStandard ECMA-335 - Common Language Infrastructure (CLI).

Dotyczy