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

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

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

谢谢!

Br,米兰。

是的,使用Marshal.GetDelegateForFunctionPointer在.NET中可以进行动态P / Invoke。 请参阅Patrick Smacchia 撰写的C#2.0 Unsafe Code文章中的Delegates和unmanaged function指针部分中的以下示例:

 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); } } 

还有Junfeng Zhang描述的另一种方法,它也适用于.NET 1.1:

动态PInvoke

reflection仅适用于托管代码。

根据非托管代码的实际情况,您可以使用COM interop(对于com组件)或PInvoke(对于旧式dll)来调用非托管代码。 也许你可以编写一个围绕非托管代码的包装器来实现这一点。

不,reflection仅适用于托管代码。