當前位置: 首頁>>代碼示例>>C#>>正文


C# TypeBuilder.DefinePInvokeMethod方法代碼示例

本文整理匯總了C#中System.Reflection.Emit.TypeBuilder.DefinePInvokeMethod方法的典型用法代碼示例。如果您正苦於以下問題:C# TypeBuilder.DefinePInvokeMethod方法的具體用法?C# TypeBuilder.DefinePInvokeMethod怎麽用?C# TypeBuilder.DefinePInvokeMethod使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Reflection.Emit.TypeBuilder的用法示例。


在下文中一共展示了TypeBuilder.DefinePInvokeMethod方法的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

//引入命名空間
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");
    }
}
開發者ID:.NET開發者,項目名稱:System.Reflection.Emit,代碼行數:59,代碼來源:TypeBuilder.DefinePInvokeMethod

輸出:

Testing PInvoke method...
GetTickCount returned: 1312576235
Saving: PInvokeTest.dll


注:本文中的System.Reflection.Emit.TypeBuilder.DefinePInvokeMethod方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。