Is it possible to call unmanaged code using C# reflection from managed code?

廉价感情. 提交于 2019-12-22 07:05:43

问题


Is it possible using reflection and C# .NET to call dynamicly different function (with arguments) written in C or C++ before .NET came(unmanaged code) ?

And smole C# example if possible would be appreciated!

Thanks!

Br, Milan.


回答1:


Yes, dynamic P/Invoke is possible in .NET using Marshal.GetDelegateForFunctionPointer. See the following sample taken from the section Delegates and unmanaged function pointers from the article Writing C# 2.0 Unsafe Code by Patrick Smacchia:

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

There is also another method described by Junfeng Zhang, which also works in .NET 1.1:

Dynamic PInvoke




回答2:


Reflection only works with managed code.

Depending on what the unmanaged code actually is you could use COM interop (for com components) or PInvoke (for old-style dll's) to invoke the unmanaged code. Maybe you can write a wrapper around the unmanaged code to make this possible.




回答3:


No, Reflection is only for Managed code.



来源:https://stackoverflow.com/questions/2957411/is-it-possible-to-call-unmanaged-code-using-c-sharp-reflection-from-managed-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!