是否可以使用托管代码中的C#反射调用非托管代码?

mil*_*lan 5 .net c# reflection unmanaged managed

是否有可能使用反射和C#.NET在.NET出现之前用动态调用不同的函数(带参数)来编写(非托管代码)?

如果可能的话,smole C#示例将不胜感激!

谢谢!

Br,米兰.

Dir*_*mar 5

是的,动态 P/Invoke 在 .NET 中可以通过不同的方式实现。

LoadLibrary 和 Marshal.GetDelegateForFunctionPointer

下面的示例Marshal.GetDelegateForFunctionPointer取自Patrick Smacchia 撰写的《编写 C# 2.0 不安全代码》一文中的“委托和非托管函数指针”部分, Junfeng Zhang 的这篇旧博客文章中也提供了非常类似的示例

using System;
using System.Runtime.InteropServices;
class Program
{
     internal delegate bool DelegBeep(uint iFreq, uint iDuration);
     [DllImport("kernel32.dll")]
     internal static extern IntPtr LoadLibrary(String dllname);
     [DllImport("kernel32.dll")]
     internal static extern IntPtr GetProcAddress(IntPtr hModule,String procName);
     static void Main()
     {
          IntPtr kernel32 = LoadLibrary( "Kernel32.dll" );
          IntPtr procBeep = GetProcAddress( kernel32, "Beep" );
          DelegBeep delegBeep = Marshal.GetDelegateForFunctionPointer(procBeep , typeof( DelegBeep ) ) as DelegBeep;
          delegBeep(100,100);
     }
}
Run Code Online (Sandbox Code Playgroud)

反射.发射

此方法适用于所有版本的.NET。它在文档中用一个例子进行了描述System.Reflection.Emit.ModuleBuilder.DefinePInvokeMethod