TypeBuilder.DefinePInvokeMethod Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Definisce un PInvoke metodo.
Overload
| Nome | Descrizione |
|---|---|
| DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Definisce un |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Definisce un |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet) |
Definisce un |
DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Definisce un PInvoke metodo in base al nome, al nome della DLL in cui è definito il metodo, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi dei parametri del metodo e ai PInvoke flag.
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
Parametri
- name
- String
Nome del PInvoke metodo.
name non può contenere valori Null incorporati.
- dllName
- String
Nome della DLL in cui è definito il PInvoke metodo.
- attributes
- MethodAttributes
Attributi del metodo .
- callingConvention
- CallingConventions
Convenzione di chiamata del metodo.
- returnType
- Type
Tipo restituito del metodo.
- parameterTypes
- Type[]
Tipi dei parametri del metodo.
- nativeCallConv
- CallingConvention
Convenzione di chiamata nativa.
- nativeCharSet
- CharSet
Set di caratteri nativi del metodo.
Valori restituiti
Metodo definito PInvoke .
Eccezioni
Il metodo non è statico.
oppure
Il tipo padre è un'interfaccia.
oppure
Il metodo è astratto.
oppure
Il metodo è stato definito in precedenza.
oppure
La lunghezza di name o dllName è zero.
name o dllName è null.
Il tipo contenitore è stato creato in precedenza usando CreateType().
Esempio
Nell'esempio seguente viene illustrato come usare il DefinePInvokeMethod metodo per creare un PInvoke metodo e come aggiungere il MethodImplAttributes.PreserveSig flag ai flag di implementazione del metodo dopo aver creato MethodBuilder, usando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .
Importante
Per ottenere un valore restituito diverso da zero, è necessario aggiungere il MethodImplAttributes.PreserveSig flag .
Nell'esempio viene creato un assembly dinamico con un modulo dinamico e un singolo tipo, MyType, che contiene il PInvoke metodo . Il PInvoke metodo rappresenta la funzione Win32 GetTickCount .
Quando viene eseguito l'esempio, esegue il PInvoke metodo . Salva anche l'assembly dinamico come PInvokeTest.dll. È possibile usare il Ildasm.exe (Disassembler IL) per esaminare la classe MyType e il static (Shared in Visual Basic) PInvoke che contiene. È possibile compilare un programma Visual Basic o C# che usa il metodo MyType.GetTickCount statico includendo un riferimento alla DLL quando si esegue csc.exe o vbc.exe, ad esempio /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
Commenti
Alcuni attributi di importazione DLL (vedere la descrizione di DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Ad esempio, l'attributo MethodImplAttributes.PreserveSig di importazione DLL deve essere aggiunto dopo la creazione del PInvoke metodo, se il metodo restituisce un valore. L'esempio mostra come eseguire questa operazione.
Si applica a
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Definisce un PInvoke metodo in base al nome, al nome della DLL in cui è definito il metodo, al nome del punto di ingresso, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi dei parametri del metodo e ai PInvoke flag.
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
Parametri
- name
- String
Nome del PInvoke metodo.
name non può contenere valori Null incorporati.
- dllName
- String
Nome della DLL in cui è definito il PInvoke metodo.
- entryName
- String
Nome del punto di ingresso nella DLL.
- attributes
- MethodAttributes
Attributi del metodo .
- callingConvention
- CallingConventions
Convenzione di chiamata del metodo.
- returnType
- Type
Tipo restituito del metodo.
- parameterTypes
- Type[]
Tipi dei parametri del metodo.
- nativeCallConv
- CallingConvention
Convenzione di chiamata nativa.
- nativeCharSet
- CharSet
Set di caratteri nativi del metodo.
Valori restituiti
Metodo definito PInvoke .
Eccezioni
Il metodo non è statico.
oppure
Il tipo padre è un'interfaccia.
oppure
Il metodo è astratto.
oppure
Il metodo è stato definito in precedenza.
oppure
La lunghezza di name, dllNameo entryName è zero.
name, dllNameo entryName è null.
Il tipo contenitore è stato creato in precedenza usando CreateType().
Esempio
Nell'esempio di codice seguente viene illustrato come usare il DefinePInvokeMethod metodo per creare un PInvoke metodo e come aggiungere il flag ai flag di implementazione del MethodImplAttributes.PreserveSig metodo dopo aver creato MethodBuilder, usando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .
Importante
Per ottenere un valore restituito diverso da zero, è necessario aggiungere il MethodImplAttributes.PreserveSig flag .
Nell'esempio viene creato un assembly dinamico con un modulo dinamico e un singolo tipo, MyType, che contiene il PInvoke metodo . Il PInvoke metodo rappresenta la funzione Win32 GetTickCount .
Quando viene eseguito l'esempio, esegue il PInvoke metodo . Salva anche l'assembly dinamico come PInvokeTest.dll. È possibile usare il Ildasm.exe (Disassembler IL) per esaminare la classe MyType e il static (Shared in Visual Basic) PInvoke che contiene. È possibile compilare un programma Visual Basic o C# che usa il metodo MyType.GetTickCount statico includendo un riferimento alla DLL quando si esegue csc.exe o vbc.exe, ad esempio /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
Commenti
Alcuni attributi di importazione DLL (vedere la descrizione di DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Ad esempio, l'attributo MethodImplAttributes.PreserveSig di importazione DLL deve essere aggiunto dopo la creazione del PInvoke metodo, se il metodo restituisce un valore. L'esempio mostra come eseguire questa operazione.
Si applica a
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)
Definisce un PInvoke metodo in base al nome, al nome della DLL in cui è definito il metodo, al nome del punto di ingresso, agli attributi del metodo, alla convenzione di chiamata del metodo, al tipo restituito del metodo, ai tipi dei parametri del metodo, PInvoke ai flag e ai modificatori personalizzati per i parametri e al tipo restituito.
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
Parametri
- name
- String
Nome del PInvoke metodo.
name non può contenere valori Null incorporati.
- dllName
- String
Nome della DLL in cui è definito il PInvoke metodo.
- entryName
- String
Nome del punto di ingresso nella DLL.
- attributes
- MethodAttributes
Attributi del metodo .
- callingConvention
- CallingConventions
Convenzione di chiamata del metodo.
- returnType
- Type
Tipo restituito del metodo.
- returnTypeRequiredCustomModifiers
- Type[]
Matrice di tipi che rappresentano i modificatori personalizzati necessari, ad esempio IsConst, per il tipo restituito del metodo. Se il tipo restituito non dispone di modificatori personalizzati obbligatori, specificare null.
- returnTypeOptionalCustomModifiers
- Type[]
Matrice di tipi che rappresentano i modificatori personalizzati facoltativi, ad esempio IsConst, per il tipo restituito del metodo. Se il tipo restituito non dispone di modificatori personalizzati facoltativi, specificare null.
- parameterTypes
- Type[]
Tipi dei parametri del metodo.
- parameterTypeRequiredCustomModifiers
- Type[][]
Matrice di matrici di tipi. Ogni matrice di tipi rappresenta i modificatori personalizzati necessari per il parametro corrispondente, ad esempio IsConst. Se un particolare parametro non ha modificatori personalizzati obbligatori, specificare null anziché una matrice di tipi. Se nessuno dei parametri dispone di modificatori personalizzati necessari, specificare null invece di una matrice di matrici.
- parameterTypeOptionalCustomModifiers
- Type[][]
Matrice di matrici di tipi. Ogni matrice di tipi rappresenta i modificatori personalizzati facoltativi per il parametro corrispondente, ad esempio IsConst. Se un determinato parametro non include modificatori personalizzati facoltativi, specificare null anziché una matrice di tipi. Se nessuno dei parametri dispone di modificatori personalizzati facoltativi, specificare null invece di una matrice di matrici.
- nativeCallConv
- CallingConvention
Convenzione di chiamata nativa.
- nativeCharSet
- CharSet
Set di caratteri nativi del metodo.
Valori restituiti
Oggetto MethodBuilder che rappresenta il metodo definito PInvoke .
Eccezioni
Il metodo non è statico.
oppure
Il tipo padre è un'interfaccia.
oppure
Il metodo è astratto.
oppure
Il metodo è stato definito in precedenza.
oppure
La lunghezza di name, dllNameo entryName è zero.
oppure
La dimensione di parameterTypeRequiredCustomModifiers o parameterTypeOptionalCustomModifiers non è uguale alla dimensione di parameterTypes.
name, dllNameo entryName è null.
Il tipo è stato creato in precedenza usando CreateType().
oppure
Per il tipo dinamico corrente, la IsGenericType proprietà è true, ma la IsGenericTypeDefinition proprietà è false.
Esempio
Nell'esempio di codice seguente viene illustrato come usare il DefinePInvokeMethod metodo per creare un PInvoke metodo e come aggiungere il flag ai flag di implementazione del MethodImplAttributes.PreserveSig metodo dopo aver creato MethodBuilder, usando i MethodBuilder.GetMethodImplementationFlags metodi e MethodBuilder.SetImplementationFlags .
Nell'esempio viene creato un assembly dinamico con un modulo dinamico e un singolo tipo, MyType, che contiene il PInvoke metodo . Il PInvoke metodo rappresenta la funzione Win32 GetTickCount .
Importante
Per ottenere un valore restituito diverso da zero, è necessario aggiungere il MethodImplAttributes.PreserveSig flag .
Annotazioni
Nell'esempio viene utilizzato un overload che non specifica modificatori personalizzati. Per specificare modificatori personalizzati, modificare invece il codice di esempio per usare questo overload del metodo.
Quando viene eseguito l'esempio, esegue il PInvoke metodo . Salva anche l'assembly dinamico come PInvokeTest.dll. È possibile usare il Ildasm.exe (Disassembler IL) per esaminare la classe MyType e il static (Shared in Visual Basic) PInvoke che contiene. È possibile compilare un programma Visual Basic o C# che usa il metodo MyType.GetTickCount statico includendo un riferimento alla DLL quando si esegue csc.exe o vbc.exe, ad esempio /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
Commenti
Alcuni attributi di importazione DLL (vedere la descrizione di DllImportAttribute) non possono essere specificati come argomenti per questo metodo. Ad esempio, l'attributo MethodImplAttributes.PreserveSig di importazione DLL deve essere aggiunto dopo la creazione del PInvoke metodo, se il metodo restituisce un valore. L'esempio mostra come eseguire questa operazione.
Annotazioni
Per altre informazioni sui modificatori personalizzati, vedere ECMA C# e Common Language Infrastructure Standards (StandardECMA-335 - Common Language Infrastructure) e Standard ECMA-335 - Common Language Infrastructure (CLI).