我有 ac dll,想通过 C# 动态加载它。我这样做:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Dota2Plugins
{
class Interop
{
#region Win API
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(string lpLibFileName);
[DllImport("kernel32.dll")]
public extern static IntPtr GetProcAddress(IntPtr hLib, string lpProcName);
[DllImport("kernel32.dll")]
public extern static bool FreeLibrary(IntPtr hLib);
#endregion
private IntPtr hLib;
public Interop(String DLLPath)
{
hLib = LoadLibrary(DLLPath);
if (hLib == IntPtr.Zero)
{
throw new Exception("not found dll : " + DLLPath);
}
}
~Interop()
{
FreeLibrary(hLib);
}
public IntPtr GetIntPtr(string APIName)
{
IntPtr api = GetProcAddress(hLib, APIName);
if (api == IntPtr.Zero)
{
throw new Exception("not found api : " + APIName);
}
return api;
}
public Delegate GetDelegate(string APIName, Type t)
{
IntPtr api = GetIntPtr(APIName);
return Marshal.GetDelegateForFunctionPointer(api, t);
}
}
}
像这样加载 dll:
Interop interop = new Interop("KeyBoardHook.dll");`
但是当我运行我的应用程序时,它抛出错误:
未找到 dll:KeyBoardHook.dll
我已将 dll 复制到应用程序目录。
我使用了相对性目录和绝对目录来尝试并得到相同的错误结果。
如何在 C# 中动态加载 ac DLL 并调用 DLL 导出 api?
您提出了两个问题,第一,未找到 DLL,以及如何从 C 进行动态加载。
当尝试从 C# 32 位项目加载 X64 dll 时,这是一个常见问题。
public Interop(String DLLPath)
?也许您的应用程序目录不正确,正如 Stefan 在评论中提到的那样。
也可以尝试完整路径。
关于动态加载,这是另一个话题。您必须在 DLL 中指定参数,理论上您可以在运行时执行它们。
如果你有头文件,你可以创建一个派生自System.Dynamic.DynamicObject
并在运行时解析头文件的类,覆盖自TryInvokeMember
(一旦你得到它,你就可以解析它)。
不过我不会使用这种方法。
我不确定如果没有标题,你会如何动态地做到这一点,恐怕。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句