Is it possible using reflection and C# .NET to call dynamically different function (with arguments) written in C or C++ before .NET came (unmanaged code) ?
A small C# example if possible would be appreciated!
Yes, dynamic P/Invoke is possible in .NET in different ways.
Here's an example using Marshal.GetDelegateForFunctionPointer
taken from the section Delegates and unmanaged function pointers from the article Writing C# 2.0 Unsafe Code by Patrick Smacchia, a very similar sample is also available in this old blog post by 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);
}
}
This method work in all versions of .NET. It is described with an example in the documentation of System.Reflection.Emit.ModuleBuilder.DefinePInvokeMethod
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With