TypeBuilder.DefinePInvokeMethod Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Define un PInvoke método .
Sobrecargas
| Nombre | Description |
|---|---|
| DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Define un |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Define un |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet) |
Define un |
DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
Define un PInvoke método dado su nombre, el nombre del archivo DLL en el que se define el método, los atributos del método, la convención de llamada del método, el tipo de valor devuelto del método, los tipos de los parámetros del método y las PInvoke marcas.
public:
System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")]
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")>]
member this.DefinePInvokeMethod : string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
member this.DefinePInvokeMethod : string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder
Parámetros
- name
- String
Nombre del PInvoke método.
name no puede contener valores NULL incrustados.
- dllName
- String
Nombre del archivo DLL en el que se define el PInvoke método.
- attributes
- MethodAttributes
Atributos del método .
- callingConvention
- CallingConventions
Convención de llamada del método.
- returnType
- Type
Tipo de valor devuelto del método.
- parameterTypes
- Type[]
Los tipos de los parámetros del método.
- nativeCallConv
- CallingConvention
Convención de llamada nativa.
- nativeCharSet
- CharSet
Juego de caracteres nativo del método.
Devoluciones
Método definido PInvoke .
- Atributos
Excepciones
El método no es estático.
O bien
El tipo primario es una interfaz.
O bien
El método es abstracto.
O bien
El método se definió anteriormente.
O bien
La longitud de name o dllName es cero.
name o dllName es null.
El tipo contenedor se ha creado anteriormente mediante CreateType().
Ejemplos
En el ejemplo siguiente se muestra cómo usar el DefinePInvokeMethod método para crear un PInvoke método y cómo agregar la MethodImplAttributes.PreserveSig marca a las marcas de implementación del método después de crear , MethodBuildermediante los MethodBuilder.GetMethodImplementationFlags métodos y MethodBuilder.SetImplementationFlags .
Importante
Para obtener un valor devuelto distinto de cero, debe agregar la MethodImplAttributes.PreserveSig marca .
En el ejemplo se crea un ensamblado dinámico con un módulo dinámico y un único tipo, MyType, que contiene el PInvoke método . El PInvoke método representa la función Win32 GetTickCount .
Cuando se ejecuta el ejemplo, ejecuta el PInvoke método . También guarda el ensamblado dinámico como PInvokeTest.dll. Puede usar el
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
Comentarios
Algunos atributos de importación de DLL (vea la descripción de DllImportAttribute) no se pueden especificar como argumentos para este método. Por ejemplo, el atributo MethodImplAttributes.PreserveSig de importación de DLL debe agregarse después de crear el PInvoke método, si el método devuelve un valor. En el ejemplo se muestra cómo hacerlo.
Se aplica a
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
Define un PInvoke método dado su nombre, el nombre del archivo DLL en el que se define el método, el nombre del punto de entrada, los atributos del método, la convención de llamada del método, el tipo devuelto del método, los tipos de los parámetros del método y las PInvoke marcas.
public:
System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::String ^ entryName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")]
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")>]
member this.DefinePInvokeMethod : string * string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
member this.DefinePInvokeMethod : string * string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, entryName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder
Parámetros
- name
- String
Nombre del PInvoke método.
name no puede contener valores NULL incrustados.
- dllName
- String
Nombre del archivo DLL en el que se define el PInvoke método.
- entryName
- String
Nombre del punto de entrada en el archivo DLL.
- attributes
- MethodAttributes
Atributos del método .
- callingConvention
- CallingConventions
Convención de llamada del método.
- returnType
- Type
Tipo de valor devuelto del método.
- parameterTypes
- Type[]
Los tipos de los parámetros del método.
- nativeCallConv
- CallingConvention
Convención de llamada nativa.
- nativeCharSet
- CharSet
Juego de caracteres nativo del método.
Devoluciones
Método definido PInvoke .
- Atributos
Excepciones
El método no es estático.
O bien
El tipo primario es una interfaz.
O bien
El método es abstracto.
O bien
El método se definió anteriormente.
O bien
La longitud de name, dllNameo entryName es cero.
name, dllNameo entryName es null.
El tipo contenedor se ha creado anteriormente mediante CreateType().
Ejemplos
En el ejemplo de código siguiente se muestra cómo usar el DefinePInvokeMethod método para crear un PInvoke método y cómo agregar la MethodImplAttributes.PreserveSig marca a las marcas de implementación del método después de crear , MethodBuildermediante los MethodBuilder.GetMethodImplementationFlags métodos y MethodBuilder.SetImplementationFlags .
Importante
Para obtener un valor devuelto distinto de cero, debe agregar la MethodImplAttributes.PreserveSig marca .
En el ejemplo se crea un ensamblado dinámico con un módulo dinámico y un único tipo, MyType, que contiene el PInvoke método . El PInvoke método representa la función Win32 GetTickCount .
Cuando se ejecuta el ejemplo, ejecuta el PInvoke método . También guarda el ensamblado dinámico como PInvokeTest.dll. Puede usar el
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
Comentarios
Algunos atributos de importación de DLL (vea la descripción de DllImportAttribute) no se pueden especificar como argumentos para este método. Por ejemplo, el atributo MethodImplAttributes.PreserveSig de importación de DLL debe agregarse después de crear el PInvoke método, si el método devuelve un valor. En el ejemplo se muestra cómo hacerlo.
Se aplica a
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
- Source:
- TypeBuilder.cs
Define un PInvoke método dado su nombre, el nombre del archivo DLL en el que se define el método, el nombre del punto de entrada, los atributos del método, la convención de llamada del método, el tipo devuelto del método, los tipos de los parámetros del método, las PInvoke marcas y modificadores personalizados para los parámetros y el tipo de valor devuelto.
public:
System::Reflection::Emit::MethodBuilder ^ DefinePInvokeMethod(System::String ^ name, System::String ^ dllName, System::String ^ entryName, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ returnTypeRequiredCustomModifiers, cli::array <Type ^> ^ returnTypeOptionalCustomModifiers, cli::array <Type ^> ^ parameterTypes, cli::array <cli::array <Type ^> ^> ^ parameterTypeRequiredCustomModifiers, cli::array <cli::array <Type ^> ^> ^ parameterTypeOptionalCustomModifiers, System::Runtime::InteropServices::CallingConvention nativeCallConv, System::Runtime::InteropServices::CharSet nativeCharSet);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")]
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")>]
member this.DefinePInvokeMethod : string * string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type[] * Type[] * Type[][] * Type[][] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
member this.DefinePInvokeMethod : string * string * string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type[] * Type[] * Type[][] * Type[][] * System.Runtime.InteropServices.CallingConvention * System.Runtime.InteropServices.CharSet -> System.Reflection.Emit.MethodBuilder
Public Function DefinePInvokeMethod (name As String, dllName As String, entryName As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, returnTypeRequiredCustomModifiers As Type(), returnTypeOptionalCustomModifiers As Type(), parameterTypes As Type(), parameterTypeRequiredCustomModifiers As Type()(), parameterTypeOptionalCustomModifiers As Type()(), nativeCallConv As CallingConvention, nativeCharSet As CharSet) As MethodBuilder
Parámetros
- name
- String
Nombre del PInvoke método.
name no puede contener valores NULL incrustados.
- dllName
- String
Nombre del archivo DLL en el que se define el PInvoke método.
- entryName
- String
Nombre del punto de entrada en el archivo DLL.
- attributes
- MethodAttributes
Atributos del método .
- callingConvention
- CallingConventions
Convención de llamada del método.
- returnType
- Type
Tipo de valor devuelto del método.
- returnTypeRequiredCustomModifiers
- Type[]
Matriz de tipos que representan los modificadores personalizados necesarios, como IsConst, para el tipo de valor devuelto del método . Si el tipo de valor devuelto no tiene modificadores personalizados necesarios, especifique null.
- returnTypeOptionalCustomModifiers
- Type[]
Matriz de tipos que representan los modificadores personalizados opcionales, como IsConst, para el tipo de valor devuelto del método . Si el tipo de valor devuelto no tiene modificadores personalizados opcionales, especifique null.
- parameterTypes
- Type[]
Los tipos de los parámetros del método.
- parameterTypeRequiredCustomModifiers
- Type[][]
Matriz de matrices de tipos. Cada matriz de tipos representa los modificadores personalizados necesarios para el parámetro correspondiente, como IsConst. Si un parámetro determinado no tiene modificadores personalizados necesarios, especifique null en lugar de una matriz de tipos. Si ninguno de los parámetros tiene modificadores personalizados necesarios, especifique null en lugar de una matriz de matrices.
- parameterTypeOptionalCustomModifiers
- Type[][]
Matriz de matrices de tipos. Cada matriz de tipos representa los modificadores personalizados opcionales para el parámetro correspondiente, como IsConst. Si un parámetro determinado no tiene modificadores personalizados opcionales, especifique null en lugar de una matriz de tipos. Si ninguno de los parámetros tiene modificadores personalizados opcionales, especifique null en lugar de una matriz de matrices.
- nativeCallConv
- CallingConvention
Convención de llamada nativa.
- nativeCharSet
- CharSet
Juego de caracteres nativo del método.
Devoluciones
que MethodBuilder representa el método definido PInvoke .
- Atributos
Excepciones
El método no es estático.
O bien
El tipo primario es una interfaz.
O bien
El método es abstracto.
O bien
El método se definió anteriormente.
O bien
La longitud de name, dllNameo entryName es cero.
O bien
El tamaño de parameterTypeRequiredCustomModifiers o parameterTypeOptionalCustomModifiers no es igual al tamaño de parameterTypes.
name, dllNameo entryName es null.
El tipo se creó anteriormente mediante CreateType().
O bien
Para el tipo dinámico actual, la IsGenericType propiedad es true, pero la IsGenericTypeDefinition propiedad es false.
Ejemplos
En el ejemplo de código siguiente se muestra cómo usar el DefinePInvokeMethod método para crear un PInvoke método y cómo agregar la MethodImplAttributes.PreserveSig marca a las marcas de implementación del método después de crear , MethodBuildermediante los MethodBuilder.GetMethodImplementationFlags métodos y MethodBuilder.SetImplementationFlags .
En el ejemplo se crea un ensamblado dinámico con un módulo dinámico y un único tipo, MyType, que contiene el PInvoke método . El PInvoke método representa la función Win32 GetTickCount .
Importante
Para obtener un valor devuelto distinto de cero, debe agregar la MethodImplAttributes.PreserveSig marca .
Note
En el ejemplo se usa una sobrecarga que no especifica modificadores personalizados. Para especificar modificadores personalizados, cambie el código de ejemplo para usar esta sobrecarga de método en su lugar.
Cuando se ejecuta el ejemplo, ejecuta el PInvoke método . También guarda el ensamblado dinámico como PInvokeTest.dll. Puede usar el
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
Comentarios
Algunos atributos de importación de DLL (vea la descripción de DllImportAttribute) no se pueden especificar como argumentos para este método. Por ejemplo, el atributo MethodImplAttributes.PreserveSig de importación de DLL debe agregarse después de crear el PInvoke método, si el método devuelve un valor. En el ejemplo se muestra cómo hacerlo.
Note
Para obtener más información sobre los modificadores personalizados, consulte ECMA C# y Common Language Infrastructure Standards and Standard ECMA-335 - Common Language Infrastructure (CLI).