【发布时间】:2019-05-31 16:36:16
【问题描述】:
我有一个 c 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# 中动态加载 c DLL 并调用 DLL 导出 api ?
【问题讨论】:
-
application directory,这是exe所在的地方吗? -
欢迎来到本站。访问tour。您不想在 dll 中使用
DllImport是否有特殊原因? -
是的,我确定 dll 文件目录是正确的。我已经解决了这个问题。谢谢!
-
是的,我确定 dll 文件目录是正确的。我已经解决了这个问题。谢谢!