是否可以使用反射和 C# .NET 动态调用在 .NET 出现之前用 C 或 C++ 编写的不同函数(带参数)(非托管代码)?
如果可能的话,一个小的 C# 示例将不胜感激!
是的,动态 P/Invoke 在 .NET 中可以通过不同的方式实现。
LoadLibrary 和 Marshal.GetDelegateForFunctionPointer
这是一个使用的示例Marshal.GetDelegateForFunctionPointer
取自该部分委托和非托管函数指针从文章中编写 C# 2.0 不安全代码 http://www.c-sharpcorner.com/UploadFile/PatrickSmacchia/CSharp2UnsafeCode02162006063859AM/CSharp2UnsafeCode.aspx由帕特里克·斯马基亚 (Patrick Smacchia) 创作,这个旧版中也有一个非常相似的样本张俊峰的博客文章 https://learn.microsoft.com/en-us/archive/blogs/junfeng/dynamic-pinvoke
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。它在文档中用一个例子进行了描述System.Reflection.Emit.ModuleBuilder.DefinePInvokeMethod https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.modulebuilder.definepinvokemethod
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)