是否有可能使用C#反射的管理code调用非托管code?有可能、反射、code

2023-09-04 12:17:22 作者:少年多梦不多情°

时,可以使用反射和C#.NET来动态地调用不同的函数(参数)用C或C ++ .NET之前来到(非托管code)?

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) ?

和smole C#示例如果可能的话将AP preciated!

And smole C# example if possible would be appreciated!

谢谢!

BR, 米兰。

推荐答案

是的,动态P / Invoke是使用有可能在.NET Marshal.GetDelegateForFunctionPointer 。见从文章 编写C#2.0中的不安全code 的通过帕特里克Smacchia:

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

还有由李俊峰张,这也适用于描述的另一种方法.NET 1.1:

There is also another method described by Junfeng Zhang, which also works in .NET 1.1:

动态PInvoke的

Dynamic PInvoke