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

Is it possible to use reflection and C # .NET to call a dynamically different function (with arguments) written in C or C ++ before .NET appeared (unmanaged code)?

And the smole C # example, if possible, would be appreciated!

Thanks!

Br, Milan.

+4
source share
3 answers

Yes, dynamic P / Invoke is possible in .NET using Marshal.GetDelegateForFunctionPointer . See the following example, taken from the Delegates and Unmanaged Function Pointers section of the article Writing C # 2.0 Unsafe Code by Patrick Smackey:

 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
source

Reflection works only with managed code.

Depending on what the actual unmanaged code is, you can use COM interaction (for com components) or PInvoke (for the old-style dll) to call unmanaged code. Perhaps you can write a wrapper around unmanaged code to make this possible.

+3
source

No, Reflection is for managed code only.

0
source

Source: https://habr.com/ru/post/1311612/


All Articles