How to load an unmanaged DLL embedded in a resource

Time:2021-6-20

How to load unmanaged DLL

We always encounter the need to load unmanaged DLLs other than Win32. One of the recommended ways is to embed those unmanaged DLLs into resources, decompress and load them at the entrance. Let me see how to implement it first. First, we are ready for the demo. The new console project is as follows:

The code is as follows:

static void Main(string[] args)
        {
            UnzipAndLoad();
        }

        /// 
        ///Unzip the resource and load the unmanaged DLL
        /// 
        static void UnzipAndLoad()
        {
            var folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var dllPath = Path.Combine(folderPath, $"{nameof(Resource.pdfium)}.dll");// Decompress the path of the output
            if (!File.Exists(dllPath))
                File.WriteAllBytes(dllPath, Resource.pdfium);
            LoadDll(dllPath);// Unmanaged files should be loaded every time
        }

        /// 
        ///Loading unmanaged DLLs
        /// 
        /// 
        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);

Output:

Load library successful

In fact, there is still room for optimization of the above code. Microsoft has integrated many packages of Win32 functions. For example, we need to import commonkernel32DLL anduser32DLL. We can install it through nuget. We can add the following code in csproj (or directly search Pinvoke. Kernel32 by nuget)

Then the previous code is deletedLoadLibraryMethod to delete,LoadDllThe method is directly changed as follows:

/// 
    ///Loading unmanaged DLLs
    /// 
    /// 
    public static void LoadDll(string dllName)
    {
        var h =Kernel32.LoadLibrary(dllName);
        If (h.isinvalid) // is it invalid
        {
            Exception e = new Win32Exception();
            throw new DllNotFoundException($"Unable to load library: {dllName}", e);
        }
        Console.WriteLine("Load library successful");
    }

reference resources

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

Recommended Today

Proxydroid + WiFi settings catch packages that XX comments can’t catch

Proxydroid + WiFi settings catch packages that XX comments can’t catch 1、 Introduction to proxydroid 1. Download address Download and install proxydroid( Make sure your device is root)Click download 2. Interface introduction (1) If auto setting is not checked, we will configure it manually. (2) Host: enter the proxy server IP. (3) Port: enter the […]