本文整理汇总了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");
}
}
输出:
Testing PInvoke method... GetTickCount returned: 1312576235 Saving: PInvokeTest.dll