TypeBuilder.DefinePInvokeMethod Méthode
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Définit une PInvoke méthode.
Surcharges
| Nom | Description |
|---|---|
| DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Définit une |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Définit une |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet) |
Définit une |
DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Définit une PInvoke méthode portant son nom, le nom de la DLL dans laquelle la méthode est définie, les attributs de la méthode, la convention appelante de la méthode, le type de retour de la méthode, les types des paramètres de la méthode et les PInvoke indicateurs.
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
Paramètres
- name
- String
Nom de la PInvoke méthode.
name ne peut pas contenir de valeurs Null incorporées.
- dllName
- String
Nom de la DLL dans laquelle la PInvoke méthode est définie.
- attributes
- MethodAttributes
Attributs de la méthode.
- callingConvention
- CallingConventions
Convention d’appel de la méthode.
- returnType
- Type
Type de retour de la méthode.
- parameterTypes
- Type[]
Types des paramètres de la méthode.
- nativeCallConv
- CallingConvention
Convention d’appel native.
- nativeCharSet
- CharSet
Jeu de caractères natif de la méthode.
Retours
Méthode définie PInvoke .
Exceptions
La méthode n’est pas statique.
-ou-
Le type parent est une interface.
-ou-
La méthode est abstraite.
-ou-
La méthode a été précédemment définie.
-ou-
La longueur de name ou de dllName est égale à zéro.
name ou dllName est null.
Le type conteneur a été créé précédemment à l’aide CreateType()de .
Exemples
L’exemple suivant montre comment utiliser la DefinePInvokeMethod méthode pour créer une PInvoke méthode et comment ajouter l’indicateur MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de méthode après avoir créé le MethodBuilder, à l’aide des méthodes et MethodBuilder.SetImplementationFlags des MethodBuilder.GetMethodImplementationFlags méthodes.
Important
Pour obtenir une valeur de retour non nulle, vous devez ajouter l’indicateur MethodImplAttributes.PreserveSig .
L’exemple crée un assembly dynamique avec un module dynamique et un seul type, MyTypequi contient la PInvoke méthode. La PInvoke méthode représente la fonction Win32 GetTickCount .
Lorsque l’exemple est exécuté, il exécute la PInvoke méthode. Il enregistre également l’assembly dynamique en tant que PInvokeTest.dll. Vous pouvez utiliser le Ildasm.exe (désassembleur IL) pour examiner la classe MyType et la méthode static (Shared dans Visual Basic) PInvoke qu’elle contient. Vous pouvez compiler un programme Visual Basic ou C# qui utilise la méthode statique MyType.GetTickCount en incluant une référence à la DLL lorsque vous exécutez csc.exe ou vbc.exe; par exemple, /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
Remarques
Certains attributs d’importation DLL (voir la description de DllImportAttribute) ne peuvent pas être spécifiés en tant qu’arguments pour cette méthode. Par exemple, l’attribut MethodImplAttributes.PreserveSig d’importation DLL doit être ajouté une fois la PInvoke méthode créée, si la méthode retourne une valeur. L’exemple montre comment procéder.
S’applique à
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)
Définit une PInvoke méthode portant son nom, le nom de la DLL dans laquelle la méthode est définie, le nom du point d’entrée, les attributs de la méthode, la convention d’appel de la méthode, le type de retour de la méthode, les types des paramètres de la méthode et les PInvoke indicateurs.
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
Paramètres
- name
- String
Nom de la PInvoke méthode.
name ne peut pas contenir de valeurs Null incorporées.
- dllName
- String
Nom de la DLL dans laquelle la PInvoke méthode est définie.
- entryName
- String
Nom du point d’entrée dans la DLL.
- attributes
- MethodAttributes
Attributs de la méthode.
- callingConvention
- CallingConventions
Convention d’appel de la méthode.
- returnType
- Type
Type de retour de la méthode.
- parameterTypes
- Type[]
Types des paramètres de la méthode.
- nativeCallConv
- CallingConvention
Convention d’appel native.
- nativeCharSet
- CharSet
Jeu de caractères natif de la méthode.
Retours
Méthode définie PInvoke .
Exceptions
La méthode n’est pas statique.
-ou-
Le type parent est une interface.
-ou-
La méthode est abstraite.
-ou-
La méthode a été précédemment définie.
-ou-
Longueur de name, dllNameou entryName est zéro.
name, dllNameou entryName est null.
Le type conteneur a été créé précédemment à l’aide CreateType()de .
Exemples
L’exemple de code suivant montre comment utiliser la DefinePInvokeMethod méthode pour créer une PInvoke méthode et comment ajouter l’indicateur MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de la méthode après avoir créé le MethodBuilder, à l’aide des méthodes et MethodBuilder.SetImplementationFlags des MethodBuilder.GetMethodImplementationFlags méthodes.
Important
Pour obtenir une valeur de retour non nulle, vous devez ajouter l’indicateur MethodImplAttributes.PreserveSig .
L’exemple crée un assembly dynamique avec un module dynamique et un seul type, MyTypequi contient la PInvoke méthode. La PInvoke méthode représente la fonction Win32 GetTickCount .
Lorsque l’exemple est exécuté, il exécute la PInvoke méthode. Il enregistre également l’assembly dynamique en tant que PInvokeTest.dll. Vous pouvez utiliser le Ildasm.exe (désassembleur IL) pour examiner la classe MyType et la méthode static (Shared dans Visual Basic) PInvoke qu’elle contient. Vous pouvez compiler un programme Visual Basic ou C# qui utilise la méthode statique MyType.GetTickCount en incluant une référence à la DLL lorsque vous exécutez csc.exe ou vbc.exe; par exemple, /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
Remarques
Certains attributs d’importation DLL (voir la description de DllImportAttribute) ne peuvent pas être spécifiés en tant qu’arguments pour cette méthode. Par exemple, l’attribut MethodImplAttributes.PreserveSig d’importation DLL doit être ajouté une fois la PInvoke méthode créée, si la méthode retourne une valeur. L’exemple montre comment procéder.
S’applique à
DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)
Définit une PInvoke méthode portant son nom, le nom de la DLL dans laquelle la méthode est définie, le nom du point d’entrée, les attributs de la méthode, la convention d’appel de la méthode, le type de retour de la méthode, les types des paramètres de la méthode, les PInvoke indicateurs et les modificateurs personnalisés pour les paramètres et le type de retour.
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
Paramètres
- name
- String
Nom de la PInvoke méthode.
name ne peut pas contenir de valeurs Null incorporées.
- dllName
- String
Nom de la DLL dans laquelle la PInvoke méthode est définie.
- entryName
- String
Nom du point d’entrée dans la DLL.
- attributes
- MethodAttributes
Attributs de la méthode.
- callingConvention
- CallingConventions
Convention d’appel de la méthode.
- returnType
- Type
Type de retour de la méthode.
- returnTypeRequiredCustomModifiers
- Type[]
Tableau de types représentant les modificateurs personnalisés requis, tels que IsConst, pour le type de retour de la méthode. Si le type de retour n’a pas de modificateurs personnalisés requis, spécifiez null.
- returnTypeOptionalCustomModifiers
- Type[]
Tableau de types représentant les modificateurs personnalisés facultatifs, tels que IsConst, pour le type de retour de la méthode. Si le type de retour n’a aucun modificateur personnalisé facultatif, spécifiez null.
- parameterTypes
- Type[]
Types des paramètres de la méthode.
- parameterTypeRequiredCustomModifiers
- Type[][]
Tableau de tableaux de types. Chaque tableau de types représente les modificateurs personnalisés requis pour le paramètre correspondant, par IsConstexemple . Si un paramètre particulier n’a pas de modificateurs personnalisés requis, spécifiez null au lieu d’un tableau de types. Si aucun des paramètres n’a besoin de modificateurs personnalisés, spécifiez null plutôt qu’un tableau de tableaux.
- parameterTypeOptionalCustomModifiers
- Type[][]
Tableau de tableaux de types. Chaque tableau de types représente les modificateurs personnalisés facultatifs pour le paramètre correspondant, par IsConstexemple . Si un paramètre particulier n’a aucun modificateur personnalisé facultatif, spécifiez null au lieu d’un tableau de types. Si aucun des paramètres n’a de modificateurs personnalisés facultatifs, spécifiez null au lieu d’un tableau de tableaux.
- nativeCallConv
- CallingConvention
Convention d’appel native.
- nativeCharSet
- CharSet
Jeu de caractères natif de la méthode.
Retours
Représentant MethodBuilder la méthode définie PInvoke .
Exceptions
La méthode n’est pas statique.
-ou-
Le type parent est une interface.
-ou-
La méthode est abstraite.
-ou-
La méthode a été précédemment définie.
-ou-
Longueur de name, dllNameou entryName est zéro.
-ou-
La taille ou n’est parameterTypeRequiredCustomModifiersparameterTypeOptionalCustomModifiers pas égale à la taille de parameterTypes.
name, dllNameou entryName est null.
Le type a été créé précédemment à l’aide CreateType()de .
-ou-
Pour le type dynamique actuel, la IsGenericType propriété est true, mais la IsGenericTypeDefinition propriété est false.
Exemples
L’exemple de code suivant montre comment utiliser la DefinePInvokeMethod méthode pour créer une PInvoke méthode et comment ajouter l’indicateur MethodImplAttributes.PreserveSig aux indicateurs d’implémentation de la méthode après avoir créé le MethodBuilder, à l’aide des méthodes et MethodBuilder.SetImplementationFlags des MethodBuilder.GetMethodImplementationFlags méthodes.
L’exemple crée un assembly dynamique avec un module dynamique et un seul type, MyTypequi contient la PInvoke méthode. La PInvoke méthode représente la fonction Win32 GetTickCount .
Important
Pour obtenir une valeur de retour non nulle, vous devez ajouter l’indicateur MethodImplAttributes.PreserveSig .
Note
L’exemple utilise une surcharge qui ne spécifie pas de modificateurs personnalisés. Pour spécifier des modificateurs personnalisés, modifiez l’exemple de code pour utiliser cette surcharge de méthode à la place.
Lorsque l’exemple est exécuté, il exécute la PInvoke méthode. Il enregistre également l’assembly dynamique en tant que PInvokeTest.dll. Vous pouvez utiliser le Ildasm.exe (désassembleur IL) pour examiner la classe MyType et la méthode static (Shared dans Visual Basic) PInvoke qu’elle contient. Vous pouvez compiler un programme Visual Basic ou C# qui utilise la méthode statique MyType.GetTickCount en incluant une référence à la DLL lorsque vous exécutez csc.exe ou vbc.exe; par exemple, /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
Remarques
Certains attributs d’importation DLL (voir la description de DllImportAttribute) ne peuvent pas être spécifiés en tant qu’arguments pour cette méthode. Par exemple, l’attribut MethodImplAttributes.PreserveSig d’importation DLL doit être ajouté une fois la PInvoke méthode créée, si la méthode retourne une valeur. L’exemple montre comment procéder.
Note
Pour plus d’informations sur les modificateurs personnalisés, voir ECMA C# et Common Language Infrastructure Standards et Standard ECMA-335 - Common Language Infrastructure (CLI).