Export (0) Print
Expand All

TypeBuilder.DefinePInvokeMethod Method (String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)

Note: This method is new in the .NET Framework version 2.0.

Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the name of the entry point, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, the PInvoke flags, and custom modifiers for the parameters and return type.

Namespace: System.Reflection.Emit
Assembly: mscorlib (in mscorlib.dll)

public MethodBuilder DefinePInvokeMethod (
	string name,
	string dllName,
	string entryName,
	MethodAttributes attributes,
	CallingConventions callingConvention,
	Type returnType,
	Type[] returnTypeRequiredCustomModifiers,
	Type[] returnTypeOptionalCustomModifiers,
	Type[] parameterTypes,
	Type[][] parameterTypeRequiredCustomModifiers,
	Type[][] parameterTypeOptionalCustomModifiers,
	CallingConvention nativeCallConv,
	CharSet nativeCharSet
)
public MethodBuilder DefinePInvokeMethod (
	String name, 
	String dllName, 
	String entryName, 
	MethodAttributes attributes, 
	CallingConventions callingConvention, 
	Type returnType, 
	Type[] returnTypeRequiredCustomModifiers, 
	Type[] returnTypeOptionalCustomModifiers, 
	Type[] parameterTypes, 
	Type[][] parameterTypeRequiredCustomModifiers, 
	Type[][] parameterTypeOptionalCustomModifiers, 
	CallingConvention nativeCallConv, 
	CharSet nativeCharSet
)
public function DefinePInvokeMethod (
	name : String, 
	dllName : String, 
	entryName : String, 
	attributes : MethodAttributes, 
	callingConvention : CallingConventions, 
	returnType : Type, 
	returnTypeRequiredCustomModifiers : Type[], 
	returnTypeOptionalCustomModifiers : Type[], 
	parameterTypes : Type[], 
	parameterTypeRequiredCustomModifiers : Type[][], 
	parameterTypeOptionalCustomModifiers : Type[][], 
	nativeCallConv : CallingConvention, 
	nativeCharSet : CharSet
) : MethodBuilder

Parameters

name

The name of the PInvoke method. name cannot contain embedded nulls.

dllName

The name of the DLL in which the PInvoke method is defined.

entryName

The name of the entry point in the DLL.

attributes

The attributes of the method.

callingConvention

The method's calling convention.

returnType

The method's return type.

returnTypeRequiredCustomModifiers

An array of types representing the required custom modifiers, such as IsConst, for the return type of the method. If the return type has no required custom modifiers, specify a null reference (Nothing in Visual Basic).

returnTypeOptionalCustomModifiers

An array of types representing the optional custom modifiers, such as IsConst, for the return type of the method. If the return type has no required custom modifiers, specify a null reference (Nothing in Visual Basic).

parameterTypes

The types of the method's parameters.

parameterTypeRequiredCustomModifiers

An array of arrays of types. Each array of types represents the required custom modifiers for the corresponding parameter, such as IsConst. If a particular parameter has no required custom modifiers, specify a null reference (Nothing in Visual Basic) instead of an array of types. If none of the parameters have required custom modifiers, specify a null reference (Nothing in Visual Basic) instead of an array of arrays.

parameterTypeOptionalCustomModifiers

An array of arrays of types. Each array of types represents the optional custom modifiers for the corresponding parameter, such as IsConst. If a particular parameter has no optional custom modifiers, specify a null reference (Nothing in Visual Basic) instead of an array of types. If none of the parameters have optional custom modifiers, specify a null reference (Nothing in Visual Basic) instead of an array of arrays.

nativeCallConv

The native calling convention.

nativeCharSet

The method's native character set.

Return Value

A MethodBuilder representing the defined PInvoke method.

Exception typeCondition

ArgumentException

The method is not static.

-or-

The parent type is an interface.

-or-

The method is abstract.

-or-

The method was previously defined.

-or-

The length of name, dllName, or entryName is zero.

-or-

The size of parameterTypeRequiredCustomModifiers or parameterTypeOptionalCustomModifiers does not equal the size of parameterTypes.

ArgumentNullException

name, dllName, or entryName is a null reference (Nothing in Visual Basic).

InvalidOperationException

The type was previously created using CreateType.

-or-

For the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

Some DLL import attributes (see the description of DllImportAttribute) cannot be specified as arguments to this method. Such attributes should be set by emitting a custom attribute for the method. For example, the DLL import attribute PreserveSig is set by emitting a custom attribute; this is necessary if the PInvoke method is to be used by Visual Basic or C#. The example shows how to do this using the DefineMethod method.

NoteNote

For more information on custom modifiers, see the ECMA Partition II Metadata documentation. Partition II documentation is available online at http://msdn.microsoft.com/net/ecma/ and http://www.ecma-international.org/publications/standards/Ecma-335.htm.

The following code example demonstrates how to use the DefineMethod method to create a PInvoke method, and to apply the DllImportAttribute so that the PInvoke method can be called from Visual Basic and C#. The example creates a dynamic assembly with one dynamic module and a single type, MyType, that contains the PInvoke method. The PInvoke method is named Win32GetTickCount and represents the GetTickCount function.

NoteNote

The example code uses an overload of the DefineMethod method that does not specify custom modifiers. To specify custom modifiers, change the example code to use this method overload instead.

When the example is run, it creates a dynamic assembly and saves it as PInvokeTest.dll. You can use the MSIL Disassembler (Ildasm.exe) to examine the MyType class and the static (Shared in Visual Basic) PInvoke method it contains. You can compile a Visual Basic or C# program that uses the static MyType.Win32GetTickCount method by including a reference to the DLL when you run csc.exe or vbc.exe; for example, /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()
    {
        string EmitFileName = "PInvokeTest";

        // Create the AssemblyBuilder.
        AssemblyName asmName = new AssemblyName();
        asmName.Name = EmitFileName;
            
        AssemblyBuilder dynamicAsm = AppDomain.CurrentDomain.DefineDynamicAssembly(
            asmName, 
            AssemblyBuilderAccess.Save
        );

        // 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
        );
    
        // Create a MethodBuilder for the PInvoke method, using the
        // name "Win32GetTickCount". The Win32 function takes no
        // parameters, and returns an int.
        //
        MethodBuilder getTickCount = tb.DefineMethod( 
            "Win32GetTickCount", 
            MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig, 
            typeof(int), 
            new Type[] {} 
        );

        // The DLLImportAttribute type.
        Type diaType = typeof(DllImportAttribute);

        // Create a ConstuctorInfo for the DLLImportAttribute, specifying
        // the constructor that takes a string argument.
        ConstructorInfo ctor = diaType.GetConstructor(new Type[] {typeof(string)});

        // Create an array containing the fields of the DLLImportAttribute
        // class.
        FieldInfo[] fields = 
            new FieldInfo[] {
                                diaType.GetField("EntryPoint"),
                                diaType.GetField("ExactSpelling"),
                                diaType.GetField("PreserveSig"),
                                diaType.GetField("SetLastError"),
                                diaType.GetField("CallingConvention"),
                                diaType.GetField("CharSet"),
                                diaType.GetField("BestFitMapping"),
                                diaType.GetField("ThrowOnUnmappableChar")
                            };

        // Create an array of values to assign to the fields of the
        // DLLImportAttribute class, when constructing an attribute
        // for the Win32 GetTickCount function.
        Object[] fieldvalues = new Object[]  {
                                                 "GetTickCount",
                                                 true,
                                                 true,
                                                 true,
                                                 CallingConvention.StdCall,
                                                 CharSet.Ansi,
                                                 true,
                                                 true
                                             };

        // Construct a DLLImportAttribute for the Win32 GetTickCount
        // function, located in Kernel32.dll.
        CustomAttributeBuilder dia = new CustomAttributeBuilder( 
            ctor, 
            new Object[] {"Kernel32.dll"}, 
            fields, 
            fieldvalues
        ); 

        // Apply the DLLCustomAttribute to the PInvoke method.
        getTickCount.SetCustomAttribute(dia);

        // The PInvoke method does not have a method body. 

        // Create the class and produce the .dll file.
        tb.CreateType();
        Console.WriteLine("Saving: " + asmName.Name + ".dll");
        dynamicAsm.Save(asmName.Name + ".dll");

    }
}

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft