DLLWrapper
using System;
using System.Runtime.InteropServices;
namespace Myapp
{
public class DLLWrapper
{
///<summary>
/// API LoadLibrary
///</summary>
[DllImport("Kernel32")]
public static extern int LoadLibrary(String funcname);
///<summary>
/// API GetProcAddress
///</summary>
[DllImport("Kernel32")]
public static extern int GetProcAddress(int handle, String funcname);
///<summary>
/// API FreeLibrary
///</summary>
[DllImport("Kernel32")]
public static extern int FreeLibrary(int handle);
///<summary>
///通过非托管函数名转换为对应的委托
///</summary>
///<param name="dllModule">通过LoadLibrary获得的DLL句柄</param>
///<param name="functionName">非托管函数名</param>
///<param name="t">对应的委托类型</param>
///<returns>委托实例,可强制转换为适当的委托类型</returns>
public static Delegate GetFunctionAddress(int dllModule, string functionName, Type t)
{
int address = GetProcAddress(dllModule, functionName);
if (address == 0)
{
return null;
}
else
{
//生成委托返回
return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
}
}
///<summary>
///将表示函数地址的IntPtr实例转换成对应的委托
///</summary>
public static Delegate GetDelegateFromIntPtr(IntPtr address, Type t)
{
if (address == IntPtr.Zero)
{
return null;
}
else
{
return Marshal.GetDelegateForFunctionPointer(address, t);
}
}
///<summary>
///将表示函数地址的int转换成对应的委托,by jingzhongrong
///</summary>
public static Delegate GetDelegateFromIntPtr(int address, Type t)
{
if (address == 0)
{
return null;
}
else
{
return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
}
}
}
}
使用
using System;
using System.Text;
namespace Myapp
{
public class DesProvider
{
public delegate bool Merge_De(string stimeStr, string etimeStr, string macStr, string flg, StringBuilder mergedStr);
private readonly string dllPath = string.Empty;
private int cModule;
public DesProvider(string _desPath)
{
this.dllPath = _desPath;
}
private void LoadDLL()
{
// string dllPath = HttpContext.Current.Server.MapPath("~");
this.cModule = DLLWrapper.LoadLibrary(this.dllPath);
}
private void FreeModule()
{
DLLWrapper.FreeLibrary(this.cModule);
}
#region ---------- 公共方法 ------------
public bool Merge(string sTimeStr, string eTimeStr, string macStr, string flg, StringBuilder mergedStr)
{
bool rtv = false;
this.LoadDLL();
try
{
//包装类返回委托
Merge_De mg = (Merge_De)DLLWrapper.GetFunctionAddress(this.cModule, "Merge", typeof(Merge_De));
rtv = mg(sTimeStr, eTimeStr, macStr, flg, mergedStr);
}
catch (Exception)
{
}
finally
{
this.FreeModule();
}
return rtv;
}
}
}