views:

207

answers:

4

Hi all,

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.

A: 

No, Reflection is only for Managed code.

ho1
+3  A: 

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.

Mendelt
This is not a 100% correct. Reflection (in the general sense as described in http://en.wikipedia.org/wiki/Reflection_%28computer_science%29) is not limited to managed code.
0xA3
Writting around wrapper is excluded because first one does not have code and second, if it goes without wrapping ...one should not wrapp :)
milan
A: 

Why do you want to use reflection instead of just P/Invoke?

Tigraine
+2  A: 

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

0xA3
Thanks for fast answer! Your described method for calling unmanaged function residing in ".dll". Does the same method holds for calling methods residing in ".exe" and ".lib" ?
milan