C#加载非.net的DLL
1.静态加载
[DLLImport("DLLName","FunctionName") public static extern void FunctionName(参数定义)
2.动态加载
单独用一个工具类提供DLL动态加载帮助
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) {
if(hLib==0) return null; IntPtr api = GetProcAddress(hLib, APIName); return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t); } }
使用:
public delegate bool Function(参数定义); DllInvoke dll = new DllInvoke(strSeedKeyPath); Function func= (Seed2key)dll.Invoke("seed2Key", typeof(Seed2key)); func(参数);
浙公网安备 33010602011771号