ModuleBuilder.DefinePInvokeMethod Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Define um PInvoke método.
Sobrecargas
| Name | Description |
|---|---|
| DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Define um |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Define um |
DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Define um PInvoke método com o nome especificado, o nome da DLL em que o método está definido, os atributos do método, a convenção de chamada do método, o tipo de retorno do método, os tipos dos parâmetros do método e os 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
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
Parâmetros
- name
- String
O nome do PInvoke método.
name não pode conter nulos embutidos.
- dllName
- String
O nome da DLL em que o PInvoke método está definido.
- attributes
- MethodAttributes
Os atributos do método.
- callingConvention
- CallingConventions
O método chama convenção.
- returnType
- Type
O tipo de retorno do método.
- parameterTypes
- Type[]
Os tipos de parâmetros do método.
- nativeCallConv
- CallingConvention
A convenção de chamadas nativas.
- nativeCharSet
- CharSet
O conjunto de caracteres nativo do método.
Devoluções
O método definido PInvoke .
Exceções
O método não é estático nem se o tipo de contenção for uma interface.
-ou-
O método é abstrato.
-ou-
O método já estava definido.
name ou dllName é null.
O tipo de contenção foi previamente criado usando CreateType()
Exemplos
O exemplo seguinte ilustra a utilização do método DefinePInvokeMethod para criar um método MethodBuilder para um método externo não gerido, MessageBoxA, na API Windows. O exemplo mostra uma caixa de mensagem com os botões Retry e Cancel , e mostra o valor de retorno da caixa de mensagem.
Importante
Para obter um valor de retorno diferente de zero, deve adicionar MethodImplAttributes.PreserveSig às flags de implementação do método depois de criar o MethodBuilder, usando os MethodBuilder.GetMethodImplementationFlags métodos e MethodBuilder.SetImplementationFlags .
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
namespace PInvoke
{
public class Example
{
const int MB_RETRYCANCEL = 5;
static void Main()
{
AssemblyName myAssemblyName = new AssemblyName("TempAssembly");
// Define a dynamic assembly in the current application domain.
AssemblyBuilder myAssemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
myAssemblyName, AssemblyBuilderAccess.Run);
// Define a dynamic module in "TempAssembly" assembly.
ModuleBuilder myModuleBuilder =
myAssemblyBuilder.DefineDynamicModule("TempModule");
Type[] paramTypes = { typeof(int), typeof(string), typeof(string), typeof(int) };
// Define a PInvoke method.
MethodBuilder piMethodBuilder = myModuleBuilder.DefinePInvokeMethod(
"MessageBoxA",
"user32.dll",
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
CallingConventions.Standard,
typeof(int),
paramTypes,
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.
piMethodBuilder.SetImplementationFlags(
piMethodBuilder.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);
// Create global methods.
myModuleBuilder.CreateGlobalFunctions();
// Arguments for calling the method.
Object[] arguments = { 0, "Hello World", "Title", MB_RETRYCANCEL };
MethodInfo pinvokeMethod = myModuleBuilder.GetMethod("MessageBoxA");
Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...");
Console.WriteLine("Message box returned: {0}",
pinvokeMethod.Invoke(null, arguments));
}
}
}
/* This code example produces input similar to the following:
Testing module-level PInvoke method created with DefinePInvokeMethod...
Message box returned: 4
*/
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices
Namespace PInvoke
Public Class Example
Const MB_RETRYCANCEL As Integer = 5
Shared Sub Main()
Dim myAssemblyName As New AssemblyName("TempAssembly")
' Define a dynamic assembly in the current application domain.
Dim myAssemblyBuilder As AssemblyBuilder = _
AppDomain.CurrentDomain.DefineDynamicAssembly( _
myAssemblyName, AssemblyBuilderAccess.Run)
' Define a dynamic module in "TempAssembly" assembly.
Dim myModuleBuilder As ModuleBuilder = _
myAssemblyBuilder.DefineDynamicModule("TempModule")
Dim paramTypes() As Type = _
{ GetType(Integer), GetType(string), GetType(string), GetType(Integer) }
' Define a PInvoke method.
Dim piMethodBuilder As MethodBuilder = myModuleBuilder.DefinePInvokeMethod( _
"MessageBoxA", _
"user32.dll", _
MethodAttributes.Public Or MethodAttributes.Static Or MethodAttributes.PinvokeImpl, _
CallingConventions.Standard, _
GetType(Integer), _
paramTypes, _
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.
piMethodBuilder.SetImplementationFlags( _
piMethodBuilder.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig)
' Create global methods.
myModuleBuilder.CreateGlobalFunctions()
' Arguments for calling the method.
Dim arguments() As Object= { 0, "Hello World", "Title", MB_RETRYCANCEL }
Dim pinvokeMethod As MethodInfo = _
myModuleBuilder.GetMethod("MessageBoxA")
Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...")
Console.WriteLine("Message box returned: {0}", _
pinvokeMethod.Invoke(Nothing, arguments))
End Sub
End Class
End Namespace
' This code example produces input similar to the following:
'
'Testing module-level PInvoke method created with DefinePInvokeMethod...
'Message box returned: 4
Observações
Alguns atributos de importação DLL (ver a descrição de System.Runtime.InteropServices.DllImportAttribute) não podem ser especificados como argumentos deste método. Tais atributos devem ser definidos emitindo um atributo personalizado para o método. Por exemplo, o atributo PreserveSig de importação DLL é definido emitindo um atributo personalizado.
Aplica-se a
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Define um PInvoke método com o nome especificado, o nome da DLL em que o método está definido, os atributos do método, a convenção de chamada do método, o tipo de retorno do método, os tipos dos parâmetros do método e os 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
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
Parâmetros
- name
- String
O nome do PInvoke método.
name não pode conter nulos embutidos.
- dllName
- String
O nome da DLL em que o PInvoke método está definido.
- entryName
- String
O nome do ponto de entrada na DLL.
- attributes
- MethodAttributes
Os atributos do método.
- callingConvention
- CallingConventions
O método chama convenção.
- returnType
- Type
O tipo de retorno do método.
- parameterTypes
- Type[]
Os tipos de parâmetros do método.
- nativeCallConv
- CallingConvention
A convenção de chamadas nativas.
- nativeCharSet
- CharSet
O conjunto de caracteres nativo do método.
Devoluções
O método definido PInvoke .
Exceções
O método não é estático ou se o tipo de contenção for uma interface ou se o método for abstrato de se o método foi previamente definido.
name ou dllName é null.
O tipo de contenção foi previamente criado usando CreateType()
Exemplos
O exemplo seguinte ilustra a utilização do método DefinePInvokeMethod para criar um método MethodBuilder para um método externo não gerido, MessageBoxA, na API Windows. O exemplo mostra uma caixa de mensagem com os botões Retry e Cancel , e mostra o valor de retorno da caixa de mensagem.
Importante
Para obter um valor de retorno diferente de zero, deve adicionar MethodImplAttributes.PreserveSig às flags de implementação do método depois de criar o MethodBuilder, usando os MethodBuilder.GetMethodImplementationFlags métodos e MethodBuilder.SetImplementationFlags .
Este exemplo usa uma sobrecarga diferente do DefinePInvokeMethod método, mas a técnica é a mesma.
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
namespace PInvoke
{
public class Example
{
const int MB_RETRYCANCEL = 5;
static void Main()
{
AssemblyName myAssemblyName = new AssemblyName("TempAssembly");
// Define a dynamic assembly in the current application domain.
AssemblyBuilder myAssemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
myAssemblyName, AssemblyBuilderAccess.Run);
// Define a dynamic module in "TempAssembly" assembly.
ModuleBuilder myModuleBuilder =
myAssemblyBuilder.DefineDynamicModule("TempModule");
Type[] paramTypes = { typeof(int), typeof(string), typeof(string), typeof(int) };
// Define a PInvoke method.
MethodBuilder piMethodBuilder = myModuleBuilder.DefinePInvokeMethod(
"MessageBoxA",
"user32.dll",
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
CallingConventions.Standard,
typeof(int),
paramTypes,
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.
piMethodBuilder.SetImplementationFlags(
piMethodBuilder.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);
// Create global methods.
myModuleBuilder.CreateGlobalFunctions();
// Arguments for calling the method.
Object[] arguments = { 0, "Hello World", "Title", MB_RETRYCANCEL };
MethodInfo pinvokeMethod = myModuleBuilder.GetMethod("MessageBoxA");
Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...");
Console.WriteLine("Message box returned: {0}",
pinvokeMethod.Invoke(null, arguments));
}
}
}
/* This code example produces input similar to the following:
Testing module-level PInvoke method created with DefinePInvokeMethod...
Message box returned: 4
*/
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.InteropServices
Namespace PInvoke
Public Class Example
Const MB_RETRYCANCEL As Integer = 5
Shared Sub Main()
Dim myAssemblyName As New AssemblyName("TempAssembly")
' Define a dynamic assembly in the current application domain.
Dim myAssemblyBuilder As AssemblyBuilder = _
AppDomain.CurrentDomain.DefineDynamicAssembly( _
myAssemblyName, AssemblyBuilderAccess.Run)
' Define a dynamic module in "TempAssembly" assembly.
Dim myModuleBuilder As ModuleBuilder = _
myAssemblyBuilder.DefineDynamicModule("TempModule")
Dim paramTypes() As Type = _
{ GetType(Integer), GetType(string), GetType(string), GetType(Integer) }
' Define a PInvoke method.
Dim piMethodBuilder As MethodBuilder = myModuleBuilder.DefinePInvokeMethod( _
"MessageBoxA", _
"user32.dll", _
MethodAttributes.Public Or MethodAttributes.Static Or MethodAttributes.PinvokeImpl, _
CallingConventions.Standard, _
GetType(Integer), _
paramTypes, _
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.
piMethodBuilder.SetImplementationFlags( _
piMethodBuilder.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig)
' Create global methods.
myModuleBuilder.CreateGlobalFunctions()
' Arguments for calling the method.
Dim arguments() As Object= { 0, "Hello World", "Title", MB_RETRYCANCEL }
Dim pinvokeMethod As MethodInfo = _
myModuleBuilder.GetMethod("MessageBoxA")
Console.WriteLine("Testing module-level PInvoke method created with DefinePInvokeMethod...")
Console.WriteLine("Message box returned: {0}", _
pinvokeMethod.Invoke(Nothing, arguments))
End Sub
End Class
End Namespace
' This code example produces input similar to the following:
'
'Testing module-level PInvoke method created with DefinePInvokeMethod...
'Message box returned: 4
Observações
Alguns atributos de importação de DLL (ver a descrição de DllImportAttribute) não podem ser especificados como argumentos deste método. Tais atributos devem ser definidos emitindo um atributo personalizado para o método. Por exemplo, o atributo PreserveSig de importação DLL é definido emitindo um atributo personalizado.