开发者

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

开发者 https://www.devze.com 2023-01-01 17:50 出处:网络
Is it possible using reflection and C# .NET to 开发者_JAVA百科call dynamically different function (with arguments) written in C or C++ before .NET came (unmanaged code) ?

Is it possible using reflection and C# .NET to 开发者_JAVA百科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.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号