Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 860
milan Avatar asked Jun 02 '10 11:06

milan


1 Answers

Yes, dynamic P/Invoke is possible in .NET in different ways.

LoadLibrary and Marshal.GetDelegateForFunctionPointer

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

Reflection.Emit

This method work in all versions of .NET. It is described with an example in the documentation of System.Reflection.Emit.ModuleBuilder.DefinePInvokeMethod

like image 104
Dirk Vollmar Avatar answered Sep 22 '22 18:09

Dirk Vollmar