TypeBuilder.DefinePInvokeMethod 메서드

정의

PInvoke 메서드를 정의합니다.

오버로드

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

해당 이름, 메서드가 정의된 DLL의 이름, 메서드의 특성, 메서드의 호출 규칙, 메서드의 반환 형식, 메서드의 매개 변수 형식 및 PInvoke 플래그를 지정하여 PInvoke 메서드를 정의합니다.

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

해당 이름, 메서드가 정의된 DLL의 이름, 진입점의 이름, 메서드의 특성, 메서드의 호출 규칙, 메서드의 반환 형식, 메서드의 매개 변수 형식 및 PInvoke 플래그를 지정하여 PInvoke 메서드를 정의합니다.

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

해당 이름, 메서드가 정의된 DLL의 이름, 진입점의 이름, 메서드의 특성, 메서드의 호출 규칙, 메서드의 반환 형식, 메서드의 매개 변수 형식, PInvoke 플래그, 매개 변수/반환 형식에 대한 사용자 지정 한정자를 지정하여 PInvoke 메서드를 정의합니다.

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

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

해당 이름, 메서드가 정의된 DLL의 이름, 메서드의 특성, 메서드의 호출 규칙, 메서드의 반환 형식, 메서드의 매개 변수 형식 및 PInvoke 플래그를 지정하여 PInvoke 메서드를 정의합니다.

public:
 System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
member this.DefinePInvokeMethod : string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder

매개 변수

name
String

PInvoke 메서드의 이름입니다. name에는 내장된 null이 포함될 수 없습니다.

dllName
String

PInvoke 메서드가 정의된 DLL의 이름입니다.

attributes
MethodAttributes

메서드의 특성입니다.

callingConvention
CallingConventions

메서드의 호출 규칙입니다.

returnType
Type

메서드의 반환 형식입니다.

parameterTypes
Type[]

메서드 매개 변수의 형식입니다.

nativeCallConv
CallingConvention

네이티브 호출 규칙입니다.

nativeCharSet
CharSet

메서드의 네이티브 문자 집합입니다.

반환

정의된 PInvoke 메서드입니다.

예외

메서드가 정적이 아닙니다.

또는

부모 형식이 인터페이스입니다.

또는

abstract 메서드입니다.

또는

메서드가 이전에 정의되었습니다.

또는

name 또는 dllName의 길이가 0입니다.

name 또는 dllNamenull인 경우

포함하는 형식은 CreateType()을 사용하여 이전에 만든 것입니다.

예제

다음 예제에서는 메서드를 사용 하 여 DefinePInvokeMethod 메서드를 만드는 PInvoke 방법 및 메서드를 사용 하 여를 만든 MethodBuilder후 메서드 구현 플래그에 플래그를 추가 MethodImplAttributes.PreserveSig 하는 방법을 보여 MethodBuilder.GetMethodImplementationFlags 줍니다는 및 MethodBuilder.SetImplementationFlags 메서드.

중요

0이 아닌 반환 값을 얻으려면 플래그를 MethodImplAttributes.PreserveSig 추가해야 합니다.

이 예제에서는 메서드를 포함하는 하나의 동적 모듈과 단일 형식인 MyType를 사용하여 동적 어셈블리를 PInvoke 만듭니다. 메서드는 PInvoke Win32 GetTickCount 함수를 나타냅니다.

예제가 실행되면 메서드를 PInvoke 실행합니다. 또한 동적 어셈블리를 PInvokeTest.dll 저장합니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 클래스 및 static 클래스에 포함된 (SharedVisual Basic의 경우) PInvoke 메서드를 검사 MyType 할 수 있습니다. csc.exe 또는 vbc.exe 실행할 때 DLL에 대한 참조를 포함하여 정적 MyType.GetTickCount 메서드를 사용하는 Visual Basic 또는 C# 프로그램을 컴파일할 수 있습니다(예 /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대한 인수로 지정할 수 없습니다. 예를 들어 메서드가 값을 반환하는 경우 메서드를 PInvoke 만든 후에 DLL 가져오기 특성을 MethodImplAttributes.PreserveSig 추가해야 합니다. 이 예제에서는 이 작업을 수행하는 방법을 보여줍니다.

적용 대상

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

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

해당 이름, 메서드가 정의된 DLL의 이름, 진입점의 이름, 메서드의 특성, 메서드의 호출 규칙, 메서드의 반환 형식, 메서드의 매개 변수 형식 및 PInvoke 플래그를 지정하여 PInvoke 메서드를 정의합니다.

public:
 System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::String ^ entryName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
member this.DefinePInvokeMethod : string * string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, entryName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder

매개 변수

name
String

PInvoke 메서드의 이름입니다. name에는 내장된 null이 포함될 수 없습니다.

dllName
String

PInvoke 메서드가 정의된 DLL의 이름입니다.

entryName
String

DLL의 진입점 이름입니다.

attributes
MethodAttributes

메서드의 특성입니다.

callingConvention
CallingConventions

메서드의 호출 규칙입니다.

returnType
Type

메서드의 반환 형식입니다.

parameterTypes
Type[]

메서드 매개 변수의 형식입니다.

nativeCallConv
CallingConvention

네이티브 호출 규칙입니다.

nativeCharSet
CharSet

메서드의 네이티브 문자 집합입니다.

반환

정의된 PInvoke 메서드입니다.

예외

메서드가 정적이 아닙니다.

또는

부모 형식이 인터페이스입니다.

또는

abstract 메서드입니다.

또는

메서드가 이전에 정의되었습니다.

또는

name, dllName 또는 entryName의 길이가 0입니다.

name, dllName 또는 entryNamenull입니다.

포함하는 형식은 CreateType()을 사용하여 이전에 만든 것입니다.

예제

다음 코드 예제를 사용 DefinePInvokeMethod 하는 방법을 보여 줍니다.는 메서드를 만드는 PInvoke 방법 및 메서드를 사용 하 여를 만든 MethodBuilder후 메서드 구현 플래그에 플래그를 MethodBuilder.GetMethodImplementationFlags 추가 MethodImplAttributes.PreserveSig 하는 방법 및 MethodBuilder.SetImplementationFlags 메서드.

중요

0이 아닌 반환 값을 얻으려면 플래그를 MethodImplAttributes.PreserveSig 추가해야 합니다.

이 예제에서는 메서드를 포함하는 하나의 동적 모듈과 단일 형식인 MyType를 사용하여 동적 어셈블리를 PInvoke 만듭니다. 메서드는 PInvoke Win32 GetTickCount 함수를 나타냅니다.

예제가 실행되면 메서드를 PInvoke 실행합니다. 또한 동적 어셈블리를 PInvokeTest.dll 저장합니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 클래스 및 static 클래스에 포함된 (SharedVisual Basic의 경우) PInvoke 메서드를 검사 MyType 할 수 있습니다. csc.exe 또는 vbc.exe 실행할 때 DLL에 대한 참조를 포함하여 정적 MyType.GetTickCount 메서드를 사용하는 Visual Basic 또는 C# 프로그램을 컴파일할 수 있습니다(예 /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대한 인수로 지정할 수 없습니다. 예를 들어 메서드가 값을 반환하는 경우 메서드를 PInvoke 만든 후에 DLL 가져오기 특성을 MethodImplAttributes.PreserveSig 추가해야 합니다. 이 예제에서는 이 작업을 수행하는 방법을 보여줍니다.

적용 대상

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

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

해당 이름, 메서드가 정의된 DLL의 이름, 진입점의 이름, 메서드의 특성, 메서드의 호출 규칙, 메서드의 반환 형식, 메서드의 매개 변수 형식, PInvoke 플래그, 매개 변수/반환 형식에 대한 사용자 지정 한정자를 지정하여 PInvoke 메서드를 정의합니다.

public:
 System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::String ^ entryName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ 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

매개 변수

name
String

PInvoke 메서드의 이름입니다. name에는 내장된 null이 포함될 수 없습니다.

dllName
String

PInvoke 메서드가 정의된 DLL의 이름입니다.

entryName
String

DLL의 진입점 이름입니다.

attributes
MethodAttributes

메서드의 특성입니다.

callingConvention
CallingConventions

메서드의 호출 규칙입니다.

returnType
Type

메서드의 반환 형식입니다.

returnTypeRequiredCustomModifiers
Type[]

메서드의 반환 형식에 대한 필수 사용자 지정 한정자를 나타내는 형식의 배열(예: IsConst)입니다. 반환 형식에 필수 사용자 지정 한정자가 없으면 null을 지정합니다.

returnTypeOptionalCustomModifiers
Type[]

메서드의 반환 형식에 대한 선택적 사용자 지정 한정자를 나타내는 형식의 배열(예: IsConst)입니다. 반환 형식에 선택적 사용자 지정 한정자가 없으면 null을 지정합니다.

parameterTypes
Type[]

메서드 매개 변수의 형식입니다.

parameterTypeRequiredCustomModifiers
Type[][]

형식 배열의 배열입니다. 각 형식의 배열은 해당 매개 변수에 필요한 사용자 지정 한정자를 나타냅니다(예: IsConst). 특정 매개 변수에 필수 사용자 지정 한정자가 없는 경우 형식 배열 대신 null을 지정합니다. 매개 변수에 필수 사용자 지정 한정자가 없는 경우 형식 배열 대신 null을 지정합니다.

parameterTypeOptionalCustomModifiers
Type[][]

형식 배열의 배열입니다. 각 형식의 배열은 해당 매개 변수의 선택적 사용자 지정 한정자를 나타냅니다(예: IsConst). 특정 매개 변수에 선택적 사용자 지정 한정자가 없는 경우 형식 배열 대신 null을 지정합니다. 매개 변수에 선택적 사용자 지정 한정자가 없는 경우 형식 배열 대신 null을 지정합니다.

nativeCallConv
CallingConvention

네이티브 호출 규칙입니다.

nativeCharSet
CharSet

메서드의 네이티브 문자 집합입니다.

반환

정의된 PInvoke 메서드를 나타내는 MethodBuilder입니다.

예외

메서드가 정적이 아닙니다.

또는

부모 형식이 인터페이스입니다.

또는

abstract 메서드입니다.

또는

메서드가 이전에 정의되었습니다.

또는

name, dllName 또는 entryName의 길이가 0입니다.

또는

parameterTypeRequiredCustomModifiers 또는 parameterTypeOptionalCustomModifiers의 크기가 parameterTypes의 크기와 같지 않습니다.

name, dllName 또는 entryNamenull입니다.

CreateType()을 사용하여 이전에 형식을 만들었습니다.

또는

현재 동적 형식에 대해 IsGenericType 속성은 true지만 IsGenericTypeDefinition 속성은 false입니다.

예제

다음 코드 예제를 사용 DefinePInvokeMethod 하는 방법을 보여 줍니다.는 메서드를 만드는 PInvoke 방법 및 메서드를 사용 하 여를 만든 MethodBuilder후 메서드 구현 플래그에 플래그를 MethodBuilder.GetMethodImplementationFlags 추가 MethodImplAttributes.PreserveSig 하는 방법 및 MethodBuilder.SetImplementationFlags 메서드.

이 예제에서는 메서드를 포함하는 하나의 동적 모듈과 단일 형식인 MyType를 사용하여 동적 어셈블리를 PInvoke 만듭니다. 메서드는 PInvoke Win32 GetTickCount 함수를 나타냅니다.

중요

0이 아닌 반환 값을 얻으려면 플래그를 MethodImplAttributes.PreserveSig 추가해야 합니다.

참고

이 예제에서는 사용자 지정 한정자를 지정하지 않는 오버로드를 사용합니다. 사용자 지정 한정자를 지정하려면 이 메서드 오버로드를 대신 사용하도록 예제 코드를 변경합니다.

예제가 실행되면 메서드를 PInvoke 실행합니다. 또한 동적 어셈블리를 PInvokeTest.dll 저장합니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 클래스 및 static 클래스에 포함된 (SharedVisual Basic의 경우) PInvoke 메서드를 검사 MyType 할 수 있습니다. csc.exe 또는 vbc.exe 실행할 때 DLL에 대한 참조를 포함하여 정적 MyType.GetTickCount 메서드를 사용하는 Visual Basic 또는 C# 프로그램을 컴파일할 수 있습니다(예 /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대한 인수로 지정할 수 없습니다. 예를 들어 메서드가 값을 반환하는 경우 메서드를 PInvoke 만든 후에 DLL 가져오기 특성을 MethodImplAttributes.PreserveSig 추가해야 합니다. 이 예제에서는 이 작업을 수행하는 방법을 보여줍니다.

참고

사용자 지정 한정자에 대한 자세한 내용은 ECMA C# 및 공용 언어 인프라 표준표준 ECMA-335 - CLI(공용 언어 인프라)를 참조하세요.

적용 대상