首先我们用[DllImport("kernel32.dll")]private extern static IntPtr LoadLibrary(String path);[DllImport("kernel32.dll")]private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);[DllImport("kernel32.dll")]private extern static bool FreeLibrary(IntPtr lib);分别取得了LoadLibrary和GetProcAddress函数的地址,再通过这两个函数来取得我们的DLL里面的函数。我们可以先用Server.MapPath(@"~/Bin/Judge.dll")来取得我们的DLL的物理路径,然后再用LoadLibrary进行载入,最后用GetProcAddress取得要用的函数地址以下自定义类的代码完成LoadLibrary的装载和函数调用:
public class DllInvoke {
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(String path);
[DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
[DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
private IntPtr hLib;
public DllInvoke(String DLLPath)
{
hLib = LoadLibrary(DLLPath);
}
~DllInvoke()
{
FreeLibrary(hLib);
}
//将要执行的函数转换为委托
public Delegate Invoke(String APIName,Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
return (Delegate)Marshal.GetDelegateForFunctionPointer(api,t);
}
}
我自己使用的代碼:
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(String path);
[DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
[DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
public delegate int GetFileId([MarshalAs(UnmanagedType.LPTStr)] StringBuilder fileName, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder certSubjectName);
public static bool invokeDLL(string filename)
{
IntPtr hLib;
string dllPath = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "GetFileId.dll");
hLib = LoadLibrary(dllPath);
IntPtr api = GetProcAddress(hLib, "GetFileId");
GetFileId getFileId = (GetFileId)Marshal.GetDelegateForFunctionPointer(api, typeof(GetFileId));
long fileId = getFileId(new StringBuilder(filename), new StringBuilder(FTPNET.certValidator.CertName));
FreeLibrary(hLib);
}