62,244
社区成员




//动态加载dll类
class DllInvoke
{
[DllImport("kernel32.dll",SetLastError=true)]
private extern static IntPtr LoadLibraryEx(String libPath,IntPtr hFile,Int32 dwFlag);
[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 libPath)
{
问题就在这,老说加载失败(hLib=0),Marshal.GetLastWin32Error()为:183.
换成LoadLibraryEx也是一样。
hLib = LoadLibrary(libPath);//该路径传进来没有问题,是绝对路径
//hLib = LoadLibraryEx(libPath, IntPtr.Zero, 16);
if (hLib == IntPtr.Zero)
{
throw new Exception("LoadLibary failure!");
}
}
public Delegate GetDelegate(String func, Type t)
{
IntPtr api = GetProcAddress(hLib, func);
return api == IntPtr.Zero ? null : Marshal.GetDelegateForFunctionPointer(api, t);
}
~DllInvoke()
{
FreeLibrary(hLib);
}
}
class Encrypter
{
delegate Int32 DEncrypter(ref Byte source, Int32 sourceLen);
private String dllPath = ConfigurationManager.AppSettings.Get("Encrypt");
private DllInvoke invoke;
public Encrypter() {
String dllFilePath = System.Web.HttpContext.Current.Server.MapPath(dllPath);
invoke = new DllInvoke(dllFilePath);
}
public bool Encrypt(Byte[] source)
{
DEncrypter encrypt = (DEncrypter)invoke.GetDelegate("Encrypt", typeof(DEncrypter));
return encrypt(ref source[0], source.Length) == 0 ? true : false;
}
}