如何加载非托管dll

我们总会遇到需要加载非win32的非托管dll,这里推荐一种方式就是将那些非win32的非托管dll嵌入资源的方式,在入口解压并且加载的方式,我先来看看如何实现吧,首先我们准备好demo,新增控制台项目如下:

代码如下:

  static void main(string[] args)
        {
            unzipandload();
        }

        /// <summary>
        /// 解压资源并且加载非托管dll
        /// </summary>
        static void unzipandload()
        {
            var folderpath = path.getdirectoryname(assembly.getexecutingassembly().location);
            var dllpath = path.combine(folderpath, $"{nameof(resource.pdfium)}.dll");//解压输出的路径
            if (!file.exists(dllpath))
                file.writeallbytes(dllpath, resource.pdfium);
            loaddll(dllpath);//应该每次都加载非托管
        }

        /// <summary>
        /// 加载非托管dll
        /// </summary>
        /// <param name="dllname"></param>
        public static void loaddll(string dllname)
        {
            intptr h = loadlibrary(dllname);
            if (h == intptr.zero)
            {
                exception e = new win32exception();
                throw new dllnotfoundexception($"unable to load library: {dllname}", e);
            }

            console.writeline("load library successful");
        }

        [dllimport("kernel32", setlasterror = true, charset = charset.unicode)]
        static extern intptr loadlibrary(string lpfilename);

输出:

load library successful

其实上述代码还有优化的空间,微软集成了很多win32函数的包,例如我们要导入win32的下常见的kernel32dll和user32dll,我们可以通过nuget安装,我们可以在csproj加入以下代码(或者直接nuget搜索pinvoke.kernel32):

<itemgroup>
        <packagereference include="pinvoke.kernel32" version="0.7.104" />
  </itemgroup>

那么之前的代码删除的loadlibrary方法删除,loaddll方法则直接改为以下:

 /// <summary>
    /// 加载非托管dll
    /// </summary>
    /// <param name="dllname"></param>
    public static void loaddll(string dllname)
    {
        var h =kernel32.loadlibrary(dllname);
        if (h.isinvalid)//是否是无效的
        {
            exception e = new win32exception();
            throw new dllnotfoundexception($"unable to load library: {dllname}", e);
        }
        console.writeline("load library successful");
    }

参考

https://blog.lindexi.com/post/%e6%8e%a8%e8%8d%90%e5%ae%98%e6%96%b9%e5%bc%80%e6%ba%90-pinvoke-%e5%ba%93-%e5%8c%85%e5%90%ab%e5%a4%a7%e9%87%8f-win32-%e5%b0%81%e8%a3%85.html

以上就是c#如何加载嵌入到资源的非托管dll的详细内容,更多关于c#资源非托管dll的资料请关注www.887551.com其它相关文章!