TypeBuilder.DefinePInvokeMethod TypeBuilder.DefinePInvokeMethod TypeBuilder.DefinePInvokeMethod Method

定义

定义 PInvoke 方法。Defines a PInvoke method.

重载

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

定义 PInvoke 方法,指定方法的名称、定义方法所使用的 DLL 的名称、方法的属性、方法的调用约定、 方法的返回类型、 方法的参数类型,以及 PInvoke 标志。Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, and the PInvoke flags.

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

定义 PInvoke 方法,指定方法的名称、定义方法所使用的 DLL 的名称、入口点名称、 方法的属性、方法的调用约定、 方法的返回类型、 方法的参数类型,以及 PInvoke 标志。Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the name of the entry point, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, and the PInvoke flags.

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

定义 PInvoke 方法,指定方法的名称、定义方法所使用的 DLL 的名称、入口点名称、方法的属性、方法的调用约定、方法的返回类型、方法的参数类型、PInvoke 标志,以及参数和返回类型的自定义修饰符。Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the name of the entry point, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, the PInvoke flags, and custom modifiers for the parameters and return type.

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

定义 PInvoke 方法,指定方法的名称、定义方法所使用的 DLL 的名称、方法的属性、方法的调用约定、 方法的返回类型、 方法的参数类型,以及 PInvoke 标志。Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, and the PInvoke flags.

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

参数

name
String String String

PInvoke 方法的名称。The name of the PInvoke method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

dllName
String String String

定义 PInvoke 方法所使用的 DLL 的名称。The name of the DLL in which the PInvoke method is defined.

attributes
MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

callingConvention
CallingConventions CallingConventions CallingConventions

方法的调用约定。The method's calling convention.

returnType
Type Type Type

方法的返回类型。The method's return type.

parameterTypes
Type[]

方法参数的类型。The types of the method's parameters.

nativeCallConv
CallingConvention CallingConvention CallingConvention

本地调用约定。The native calling convention.

nativeCharSet
CharSet CharSet CharSet

方法的本地字符集。The method's native character set.

返回

已定义的 PInvoke 方法。The defined PInvoke method.

异常

此方法不是静态的。The method is not static.

- 或 --or- 此父类型为一个接口。The parent type is an interface.

-or- 这种方法是抽象的方法。The method is abstract.

-or- 此方法之前已定义。The method was previously defined.

-or- namedllName 的长度为零。The length of name or dllName is zero.

namedllNamenullname or dllName is null.

之前已使用 CreateType() 创建包含类型。The containing type has been previously created using CreateType().

示例

下面的示例演示DefinePInvokeMethod如何使用方法创建一个PInvoke方法,以及如何在创建MethodBuilder MethodBuilder.GetMethodImplementationFlags后将该MethodImplAttributes.PreserveSig标志添加到方法实现标志,方法是使用和MethodBuilder.SetImplementationFlags方法。The following example demonstrates how to use the DefinePInvokeMethod method to create a PInvoke method, and how to add the MethodImplAttributes.PreserveSig flag to the method implementation flags after you create the MethodBuilder, by using the MethodBuilder.GetMethodImplementationFlags and MethodBuilder.SetImplementationFlags methods.

重要

若要获取非零返回值,必须添加MethodImplAttributes.PreserveSig标志。To get a non-zero return value, you must add the MethodImplAttributes.PreserveSig flag.

该示例创建一个动态程序集,其中MyType PInvoke包含一个动态模块和一个包含方法的类型。The example creates a dynamic assembly with one dynamic module and a single type, MyType, that contains the PInvoke method. 方法表示 Win32 GetTickCount函数。 PInvokeThe PInvoke method represents the Win32 GetTickCount function.

运行该示例时,它将执行PInvoke方法。When the example is run, it executes the PInvoke method. 它还会将动态程序集保存为 PInvokeTest。It also saves the dynamic assembly as PInvokeTest.dll. 可以使用Ildasm (IL 拆装器)检查MyType类以及它包含的staticShared在 Visual Basic 中) PInvoke方法。You can use the Ildasm.exe (IL Disassembler) to examine the MyType class and the static (Shared in Visual Basic) PInvoke method it contains. 当你运行 csc 或 dcdiag.exe C#时,可以通过包括MyType.GetTickCount对 DLL 的引用来编译使用静态方法的 Visual Basic 或程序; 例如, /r:PInvokeTest.dllYou can compile a Visual Basic or C# program that uses the static MyType.GetTickCount method by including a reference to the DLL when you run csc.exe or vbc.exe; for example, /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

注解

无法将某些 DLL 导入属性(请DllImportAttribute参阅的说明)指定为此方法的参数。Some DLL import attributes (see the description of DllImportAttribute) cannot be specified as arguments to this method. 例如,如果方法返回值, MethodImplAttributes.PreserveSig则必须在创建PInvoke方法之后添加 DLL import 特性。For example, the DLL import attribute MethodImplAttributes.PreserveSig must be added after the PInvoke method is created, if the method returns a value. 此示例演示如何执行此操作。The example shows how to do this.

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

定义 PInvoke 方法,指定方法的名称、定义方法所使用的 DLL 的名称、入口点名称、 方法的属性、方法的调用约定、 方法的返回类型、 方法的参数类型,以及 PInvoke 标志。Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the name of the entry point, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, and the PInvoke flags.

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

参数

name
String String String

PInvoke 方法的名称。The name of the PInvoke method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

dllName
String String String

定义 PInvoke 方法所使用的 DLL 的名称。The name of the DLL in which the PInvoke method is defined.

entryName
String String String

DLL 中入口点的名称。The name of the entry point in the DLL.

attributes
MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

callingConvention
CallingConventions CallingConventions CallingConventions

方法的调用约定。The method's calling convention.

returnType
Type Type Type

方法的返回类型。The method's return type.

parameterTypes
Type[]

方法参数的类型。The types of the method's parameters.

nativeCallConv
CallingConvention CallingConvention CallingConvention

本地调用约定。The native calling convention.

nativeCharSet
CharSet CharSet CharSet

方法的本地字符集。The method's native character set.

返回

已定义的 PInvoke 方法。The defined PInvoke method.

异常

此方法不是静态的。The method is not static.

- 或 --or- 此父类型为一个接口。The parent type is an interface.

-or- 这种方法是抽象的方法。The method is abstract.

- 或 --or- 此方法之前已定义。The method was previously defined.

-or- namedllNameentryName 的长度为零。The length of name, dllName, or entryName is zero.

namedllNameentryNamenullname, dllName, or entryName is null.

之前已使用 CreateType() 创建包含类型。The containing type has been previously created using CreateType().

示例

下面的代码DefinePInvokeMethod示例演示如何使用方法来PInvoke创建方法, MethodImplAttributes.PreserveSig以及如何在创建MethodBuilder MethodBuilder.GetMethodImplementationFlags后将标志添加到方法实现标志,方法是使用和MethodBuilder.SetImplementationFlags方法。The following code example demonstrates how to use the DefinePInvokeMethod method to create a PInvoke method, and how to add the MethodImplAttributes.PreserveSig flag to the method implementation flags after you create the MethodBuilder, by using the MethodBuilder.GetMethodImplementationFlags and MethodBuilder.SetImplementationFlags methods.

重要

若要获取非零返回值,必须添加MethodImplAttributes.PreserveSig标志。To get a non-zero return value, you must add the MethodImplAttributes.PreserveSig flag.

该示例创建一个动态程序集,其中MyType PInvoke包含一个动态模块和一个包含方法的类型。The example creates a dynamic assembly with one dynamic module and a single type, MyType, that contains the PInvoke method. 方法表示 Win32 GetTickCount函数。 PInvokeThe PInvoke method represents the Win32 GetTickCount function.

运行该示例时,它将执行PInvoke方法。When the example is run, it executes the PInvoke method. 它还会将动态程序集保存为 PInvokeTest。It also saves the dynamic assembly as PInvokeTest.dll. 可以使用Ildasm (IL 拆装器)检查MyType类以及它包含的staticShared在 Visual Basic 中) PInvoke方法。You can use the Ildasm.exe (IL Disassembler) to examine the MyType class and the static (Shared in Visual Basic) PInvoke method it contains. 当你运行 csc 或 dcdiag.exe C#时,可以通过包括MyType.GetTickCount对 DLL 的引用来编译使用静态方法的 Visual Basic 或程序; 例如, /r:PInvokeTest.dllYou can compile a Visual Basic or C# program that uses the static MyType.GetTickCount method by including a reference to the DLL when you run csc.exe or vbc.exe; for example, /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

注解

无法将某些 DLL 导入属性(请DllImportAttribute参阅的说明)指定为此方法的参数。Some DLL import attributes (see the description of DllImportAttribute) cannot be specified as arguments to this method. 例如,如果方法返回值, MethodImplAttributes.PreserveSig则必须在创建PInvoke方法之后添加 DLL import 特性。For example, the DLL import attribute MethodImplAttributes.PreserveSig must be added after the PInvoke method is created, if the method returns a value. 此示例演示如何执行此操作。The example shows how to do this.

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

定义 PInvoke 方法,指定方法的名称、定义方法所使用的 DLL 的名称、入口点名称、方法的属性、方法的调用约定、方法的返回类型、方法的参数类型、PInvoke 标志,以及参数和返回类型的自定义修饰符。Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the name of the entry point, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, the PInvoke flags, and custom modifiers for the parameters and return type.

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

参数

name
String String String

PInvoke 方法的名称。The name of the PInvoke method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

dllName
String String String

定义 PInvoke 方法所使用的 DLL 的名称。The name of the DLL in which the PInvoke method is defined.

parameterTypeOptionalCustomModifiers
Type[][]

由类型数组组成的数组。An array of arrays of types. 每个类型数组均表示相应参数的可选自定义修饰符,如 IsConstEach array of types represents the optional custom modifiers for the corresponding parameter, such as IsConst. 如果某个特定参数没有可选的自定义修饰符,则指定 null,而不要指定类型数组。If a particular parameter has no optional custom modifiers, specify null instead of an array of types. 如果所有参数都没有可选的自定义修饰符,则指定 null,而不要指定由数组组成的数组。If none of the parameters have optional custom modifiers, specify null instead of an array of arrays.

nativeCallConv
CallingConvention CallingConvention CallingConvention

本地调用约定。The native calling convention.

nativeCharSet
CharSet CharSet CharSet

方法的本地字符集。The method's native character set.

entryName
String String String

DLL 中入口点的名称。The name of the entry point in the DLL.

attributes
MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

callingConvention
CallingConventions CallingConventions CallingConventions

方法的调用约定。The method's calling convention.

returnType
Type Type Type

方法的返回类型。The method's return type.

returnTypeRequiredCustomModifiers
Type[]

一个类型数组,表示该方法的返回类型所必需的自定义修饰符,如 IsConstAn array of types representing the required custom modifiers, such as IsConst, for the return type of the method. 如果返回类型没有所需的自定义修饰符,则指定 nullIf the return type has no required custom modifiers, specify null.

returnTypeOptionalCustomModifiers
Type[]

一个类型数组,表示该方法的返回类型的可选自定义修饰符,如 IsConstAn array of types representing the optional custom modifiers, such as IsConst, for the return type of the method. 如果返回类型没有可选的自定义修饰符,则指定 nullIf the return type has no optional custom modifiers, specify null.

parameterTypes
Type[]

方法参数的类型。The types of the method's parameters.

parameterTypeRequiredCustomModifiers
Type[][]

由类型数组组成的数组。An array of arrays of types. 每个类型数组均表示相应参数所必需的自定义修饰符,如 IsConstEach array of types represents the required custom modifiers for the corresponding parameter, such as IsConst. 如果某个特定参数没有所需的自定义修饰符,则指定 null,而不要指定类型数组。If a particular parameter has no required custom modifiers, specify null instead of an array of types. 如果所有参数都没有所需的自定义修饰符,则指定 null,而不要指定由数组组成的数组。If none of the parameters have required custom modifiers, specify null instead of an array of arrays.

返回

一个 MethodBuilder,表示所定义的 PInvoke 方法。A MethodBuilder representing the defined PInvoke method.

异常

此方法不是静态的。The method is not static.

-or- 此父类型为一个接口。The parent type is an interface.

-or- 这种方法是抽象的方法。The method is abstract.

-or- 此方法之前已定义。The method was previously defined.

-or- namedllNameentryName 的长度为零。The length of name, dllName, or entryName is zero.

-or- parameterTypeRequiredCustomModifiersparameterTypeOptionalCustomModifiers 的大小与 parameterTypes 的大小不相等。The size of parameterTypeRequiredCustomModifiers or parameterTypeOptionalCustomModifiers does not equal the size of parameterTypes.

namedllNameentryNamenullname, dllName, or entryName is null.

该类型是以前使用 CreateType() 创建的。The type was previously created using CreateType().

-or- 对于当前的动态类型,属性 IsGenericType 的值为 true,但属性 IsGenericTypeDefinition 的值为 falseFor the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

示例

下面的代码示例演示如何使用 [],type][[]][,type,type[,type][x: DefinePInvokeMethod% 2a PInvoke > 方法来创建方法,以及如何在创建后将MethodImplAttributes.PreserveSig标志添加到方法实现标志。 ] <,方法是MethodBuilder.GetMethodImplementationFlags使用和MethodBuilder.SetImplementationFlags方法。 MethodBuilderThe following code example demonstrates how to use the [], Type[], Type[], Type[][], Type[]<xref:System.Reflection.Emit.TypeBuilder.DefinePInvokeMethod%2A> method to create a PInvoke method, and how to add the MethodImplAttributes.PreserveSig flag to the method implementation flags after you create the MethodBuilder, by using the MethodBuilder.GetMethodImplementationFlags and MethodBuilder.SetImplementationFlags methods.

该示例创建一个动态程序集,其中MyType PInvoke包含一个动态模块和一个包含方法的类型。The example creates a dynamic assembly with one dynamic module and a single type, MyType, that contains the PInvoke method. 方法表示 Win32 GetTickCount函数。 PInvokeThe PInvoke method represents the Win32 GetTickCount function.

重要

若要获取非零返回值,必须添加MethodImplAttributes.PreserveSig标志。To get a non-zero return value, you must add the MethodImplAttributes.PreserveSig flag.

备注

该示例使用未指定自定义修饰符的重载。The example uses an overload that does not specify custom modifiers. 若要指定自定义修饰符,请将示例代码改为使用此方法重载。To specify custom modifiers, change the example code to use this method overload instead.

运行该示例时,它将执行PInvoke方法。When the example is run, it executes the PInvoke method. 它还会将动态程序集保存为 PInvokeTest。It also saves the dynamic assembly as PInvokeTest.dll. 可以使用Ildasm (IL 拆装器)检查MyType类以及它包含的staticShared在 Visual Basic 中) PInvoke方法。You can use the Ildasm.exe (IL Disassembler) to examine the MyType class and the static (Shared in Visual Basic) PInvoke method it contains. 当你运行 csc 或 dcdiag.exe C#时,可以通过包括MyType.GetTickCount对 DLL 的引用来编译使用静态方法的 Visual Basic 或程序; 例如, /r:PInvokeTest.dllYou can compile a Visual Basic or C# program that uses the static MyType.GetTickCount method by including a reference to the DLL when you run csc.exe or vbc.exe; for example, /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

注解

无法将某些 DLL 导入属性(请DllImportAttribute参阅的说明)指定为此方法的参数。Some DLL import attributes (see the description of DllImportAttribute) cannot be specified as arguments to this method. 例如,如果方法返回值, MethodImplAttributes.PreserveSig则必须在创建PInvoke方法之后添加 DLL import 特性。For example, the DLL import attribute MethodImplAttributes.PreserveSig must be added after the PInvoke method is created, if the method returns a value. 此示例演示如何执行此操作。The example shows how to do this.

备注

有关自定义修饰符的详细信息,请参阅 ECMA Partition II 元数据文档。For more information on custom modifiers, see the ECMA Partition II Metadata documentation. 可联机获取该文档;请参阅 MSDN 上的 ECMA C# 和公共语言基础结构标准和 Ecma International 网站上的标准 ECMA-335 - 公共语言基础结构 (CLI)The documentation is available online; see ECMA C# and Common Language Infrastructure Standards on MSDN and Standard ECMA-335 - Common Language Infrastructure (CLI) on the Ecma International Web site.

适用于