TypeBuilder.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, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet) |
Define um |
DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Define um PInvoke método com o seu nome, 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 as PInvoke bandeiras.
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.
-ou-
O tipo pai é uma interface.
-ou-
O método é abstrato.
-ou-
O método já estava definido.
-ou-
O comprimento de name ou dllName é zero.
name ou dllName é null.
O tipo de contenção foi previamente criado usando CreateType().
Exemplos
O exemplo seguinte demonstra como usar o DefinePInvokeMethod método para criar um PInvoke método, e como adicionar a MethodImplAttributes.PreserveSig flag às flags de implementação do método depois de criar os MethodBuilder, usando os MethodBuilder.GetMethodImplementationFlags métodos e.MethodBuilder.SetImplementationFlags
Importante
Para obter um valor de retorno diferente de zero, tens de adicionar a MethodImplAttributes.PreserveSig bandeira.
O exemplo cria um conjunto dinâmico com um módulo dinâmico e um único tipo, MyType, que contém o PInvoke método. O PInvoke método representa a função Win32 GetTickCount .
Quando o exemplo é executado, executa o PInvoke método. Também guarda o conjunto dinâmico como PInvokeTest.dll. Pode usar o método Ildasm.exe (IL Disassembler) para examinar a classe MyType e o método static (Shared em Visual Basic) PInvoke que contém. Pode compilar um programa Visual Basic ou C# que utilize o método estático MyType.GetTickCount incluindo uma referência à DLL quando executa csc.exe ou vbc.exe; por exemplo, /r: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
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. Por exemplo, o atributo MethodImplAttributes.PreserveSig de importação DLL deve ser adicionado após a criação do PInvoke método, se o método devolver um valor. O exemplo mostra como fazer isto.
Aplica-se a
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Define um PInvoke método com o seu nome, o nome da DLL em que o método está definido, o nome do ponto de entrada, 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 as 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-
O tipo pai é uma interface.
-ou-
O método é abstrato.
-ou-
O método já estava definido.
-ou-
O comprimento de name, dllName, ou entryName é zero.
name, dllName, ou entryName é null.
O tipo de contenção foi previamente criado usando CreateType().
Exemplos
O exemplo de código seguinte demonstra como usar o DefinePInvokeMethod método para criar um PInvoke método e como adicionar a MethodImplAttributes.PreserveSig flag às flags de implementação do método após criar os MethodBuilder, usando os MethodBuilder.GetMethodImplementationFlags métodos e.MethodBuilder.SetImplementationFlags
Importante
Para obter um valor de retorno diferente de zero, tens de adicionar a MethodImplAttributes.PreserveSig bandeira.
O exemplo cria um conjunto dinâmico com um módulo dinâmico e um único tipo, MyType, que contém o PInvoke método. O PInvoke método representa a função Win32 GetTickCount .
Quando o exemplo é executado, executa o PInvoke método. Também guarda o conjunto dinâmico como PInvokeTest.dll. Pode usar o método Ildasm.exe (IL Disassembler) para examinar a classe MyType e o método static (Shared em Visual Basic) PInvoke que contém. Pode compilar um programa Visual Basic ou C# que utilize o método estático MyType.GetTickCount incluindo uma referência à DLL quando executa csc.exe ou vbc.exe; por exemplo, /r: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
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. Por exemplo, o atributo MethodImplAttributes.PreserveSig de importação DLL deve ser adicionado após a criação do PInvoke método, se o método devolver um valor. O exemplo mostra como fazer isto.
Aplica-se a
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)
Define um PInvoke método dado o seu nome, o nome da DLL em que o método está definido, o nome do ponto de entrada, 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, as PInvoke bandeiras e modificadores personalizados para os parâmetros e o tipo de retorno.
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
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
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.
- returnTypeRequiredCustomModifiers
- Type[]
Um array de tipos que representam os modificadores personalizados necessários, como IsConst, para o tipo de retorno do método. Se o tipo de retorno não tiver modificadores personalizados obrigatórios, especifique null.
- returnTypeOptionalCustomModifiers
- Type[]
Um array de tipos que representam os modificadores personalizados opcionais, como IsConst, para o tipo de retorno do método. Se o tipo de retorno não tiver modificadores personalizados opcionais, especifique null.
- parameterTypes
- Type[]
Os tipos de parâmetros do método.
- parameterTypeRequiredCustomModifiers
- Type[][]
Uma variedade de arrays de tipos. Cada array de tipos representa os modificadores personalizados necessários para o parâmetro correspondente, como IsConst. Se um determinado parâmetro não tiver modificadores personalizados obrigatórios, especifique null em vez disso um array de tipos. Se nenhum dos parâmetros exigir modificadores personalizados, especifique null em vez de um array de arrays.
- parameterTypeOptionalCustomModifiers
- Type[][]
Uma variedade de arrays de tipos. Cada array de tipos representa os modificadores personalizados opcionais para o parâmetro correspondente, como IsConst. Se um determinado parâmetro não tiver modificadores personalizados opcionais, especifique null em vez disso um array de tipos. Se nenhum dos parâmetros tiver modificadores personalizados opcionais, especifique null em vez de um array de arrays.
- nativeCallConv
- CallingConvention
A convenção de chamadas nativas.
- nativeCharSet
- CharSet
O conjunto de caracteres nativo do método.
Devoluções
A MethodBuilder representa o método definido PInvoke .
Exceções
O método não é estático.
-ou-
O tipo pai é uma interface.
-ou-
O método é abstrato.
-ou-
O método já estava definido.
-ou-
O comprimento de name, dllName, ou entryName é zero.
-ou-
O tamanho de parameterTypeRequiredCustomModifiers ou parameterTypeOptionalCustomModifiers não é igual ao tamanho de parameterTypes.
name, dllName, ou entryName é null.
O tipo foi anteriormente criado usando CreateType().
-ou-
Para o tipo dinâmico atual, a IsGenericType propriedade é true, mas a IsGenericTypeDefinition propriedade é false.
Exemplos
O exemplo de código seguinte demonstra como usar o DefinePInvokeMethod método para criar um PInvoke método e como adicionar a MethodImplAttributes.PreserveSig flag às flags de implementação do método após criar os MethodBuilder, usando os MethodBuilder.GetMethodImplementationFlags métodos e.MethodBuilder.SetImplementationFlags
O exemplo cria um conjunto dinâmico com um módulo dinâmico e um único tipo, MyType, que contém o PInvoke método. O PInvoke método representa a função Win32 GetTickCount .
Importante
Para obter um valor de retorno diferente de zero, tens de adicionar a MethodImplAttributes.PreserveSig bandeira.
Note
O exemplo usa uma sobrecarga que não especifica modificadores personalizados. Para especificar modificadores personalizados, altere o código de exemplo para usar esta sobrecarga de métodos em vez disso.
Quando o exemplo é executado, executa o PInvoke método. Também guarda o conjunto dinâmico como PInvokeTest.dll. Pode usar o método Ildasm.exe (IL Disassembler) para examinar a classe MyType e o método static (Shared em Visual Basic) PInvoke que contém. Pode compilar um programa Visual Basic ou C# que utilize o método estático MyType.GetTickCount incluindo uma referência à DLL quando executa csc.exe ou vbc.exe; por exemplo, /r: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
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. Por exemplo, o atributo MethodImplAttributes.PreserveSig de importação DLL deve ser adicionado após a criação do PInvoke método, se o método devolver um valor. O exemplo mostra como fazer isto.
Note
Para mais informações sobre modificadores personalizados, consulte ECMA C# e Common Language Infrastructure Standards e Standard ECMA-335 - Common Language Infrastructure (CLI).