Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

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

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, and the PInvoke flags.

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[] parameterTypes,
	CallingConvention nativeCallConv,
	CharSet nativeCharSet
)
public MethodBuilder DefinePInvokeMethod (
	String name, 
	String dllName, 
	String entryName, 
	MethodAttributes attributes, 
	CallingConventions callingConvention, 
	Type returnType, 
	Type[] parameterTypes, 
	CallingConvention nativeCallConv, 
	CharSet nativeCharSet
)
public function DefinePInvokeMethod (
	name : String, 
	dllName : String, 
	entryName : String, 
	attributes : MethodAttributes, 
	callingConvention : CallingConventions, 
	returnType : Type, 
	parameterTypes : Type[], 
	nativeCallConv : CallingConvention, 
	nativeCharSet : CharSet
) : MethodBuilder
Not applicable.

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.

parameterTypes

The types of the method's parameters.

nativeCallConv

The native calling convention.

nativeCharSet

The method's native character set.

Return Value

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.

ArgumentNullException

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

InvalidOperationException

The containing type has been previously created using CreateType.

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.

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.

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 Server 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 Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

Community Additions

ADD
Show:
© 2015 Microsoft