DLLimport 虚拟路径用法

1.创建类库应用帮助类DLLWrapper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.InteropServices;

/// <summary>
/// Summary description for Class1
/// </summary>
public class DLLWrapper
{
    [DllImport("Kernel32")]
    public static extern int LoadLibrary(String funcname);
    [DllImport("Kernel32")]
    public static extern int GetProcAddress(int handle, String funcname);
    [DllImport("Kernel32")]
    public static extern int FreeLibrary(int handle);

    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);
    }

    public static Delegate GetDelegateFromIntPtr(IntPtr address, Type t)
    {
        if (address == IntPtr.Zero)
        {
            return null;
        }
        else
            return Marshal.GetDelegateForFunctionPointer(address, t);
    }

    public static Delegate GetDelegateFromIntPtr(int address, Type t)
    {
        if (address == 0)
        {
            return null;
        }
        else
            return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
    }

}

2.引用后台

  1.创建委托delegate

  public delegate bool SaveXxjToXml(string cnnStr, string xxjfile); 参数返回值,对应要引用的方法

  2.引用类库方法

     string msg = string.Empty;
     //加载类库 int hModule = DLLWrapper.LoadLibrary(Server.MapPath("~/dll/SaveToXml.dll")); if (hModule == 0) { msg = "导入信息价类库不存在,或者路径错误,请联系管理员。"; } //注册委托 SaveXxjToXml sxtx = (SaveXxjToXml)DLLWrapper.GetFunctionAddress(hModule, "SaveXxjToXml", typeof(SaveXxjToXml)); if (sxtx==null) { DLLWrapper.FreeLibrary(hModule); msg = "导入信息价类库的方法不存在,请联系管理员。"; } //调用注册后的委托 bool result = sxtx(cnnStr, Server.MapPath(path)); if (result) msg = "导入成功。"; else msg = "导入失败。";
原文地址:https://www.cnblogs.com/ruanyifeng/p/2846349.html