Understanding unmanaged dynamic link libraries

1. Unmanaged dynamic link library

    1. Unmanaged Dynamic Link Library (DLL)
        is a binary file containing executable code and data. It is designed to execute at the operating system level. Unlike managed code, unmanaged DLLs are written using native machine code and are not tied to a specific runtime environment (such as .NET Framework or .NET Core).

        Unmanaged DLLs are typically written in C, C++, or other low-level languages, and are available in multiple programming languages ​​and platforms. They provide access to operating system APIs, hardware drivers, and other system-level functionality.


    2. Use unmanaged DLL to achieve the following functions:

        (1) Access operating system-level functions:
            Unmanaged DLLs can directly call APIs provided by the operating system to access underlying functions, such as file operations, network communications, graphics processing, etc.

        (2) Calling hardware drivers:
            Unmanaged DLLs can interact with hardware devices, such as printers, cameras, sensors, etc.

        (3) Provide performance advantages:
            Since unmanaged DLLs are written using native machine code, they usually execute faster than managed code. For tasks with higher performance requirements, unmanaged DLLs can be used.


    3. When using unmanaged DLLs, you need to pay attention to the following points:

        (1) Platform compatibility:
        Unmanaged DLLs are operating system and hardware platform specific, so the correct DLL version needs to be selected based on the target platform.

        (2) Memory management:
        Unmanaged DLLs use their own memory management mechanism and may need to manually allocate and release memory. Memory leaks and access conflicts need to be handled carefully.

        (3) Security:
        Unmanaged DLLs can directly access system resources, so security issues need to be handled carefully to avoid potential vulnerabilities and attacks.

        In summary, an unmanaged dynamic link library is a binary written in native machine code to access operating system-level functionality and provide performance benefits. They are widely used in many programming languages ​​and platforms.

2. user32.dll


    1. user32.dll is an unmanaged dynamic link library (DLL) in the Windows operating system. It contains many user interface-related functions and functions.

        In C#, we can use the P/Invoke mechanism to access and call functions in user32.dll. We can call functions in user32.dll from C# by declaring the signatures of these functions in C# code and using the DllImport attribute to specify the path and function name of user32.dll.

        In this way, we can use the functions provided by user32.dll to implement user interface-related operations, such as creating and managing windows, processing mouse and keyboard input, displaying message boxes, etc. user32.dll is part of the Windows operating system, so it is available on all computers with Windows installed.


    2. In Windows systems, the user32.dll file is usually located in one of the following directories :

        C:\Windows\System32: This is the most common DLL file storage directory and contains many system-level DLL files.
        C:\Windows\SysWOW64: This is the directory for 32-bit DLL files required by 32-bit applications. Note that even on 64-bit systems, 32-bit applications still use this directory to find the 32-bit DLL files they need.
        
        The directory location is different for different versions.

3. How to call the unmanaged dynamic link library


    1. When using an unmanaged dynamic link library (DLL) in C# , you can use the Platform Invocation Services (P/Invoke) mechanism. The following are the general steps for using P/Invoke:

        (1) Import DLL: Use the DllImport attribute to declare functions in an unmanaged DLL. In the properties, specify the path and function name of the DLL.
        [DllImport("yourDLL.dll")]
        public static extern returnType functionName(parameters);

        (2) Declare function signature: Declare the function signature corresponding to the function in the unmanaged DLL in the C# code. Make sure the parameter types and return types match the functions in the DLL.
        public static extern returnType functionName(parameters);

        (3) Call function: Call the declared function in C# code.
        returnType result = functionName(arguments);


    2. Things to note:

        - The path to the unmanaged DLL should be an absolute path or located under the system path (such as Windows\System32).
        - Parameters and return types should be consistent with the definition of the function in the unmanaged DLL.
        - The calling convention of functions in unmanaged DLLs may need to be explicitly specified, such as StdCall or Cdecl.

        It should be noted that using unmanaged DLLs requires careful handling of issues such as memory management, security, and platform compatibility. Ensure memory is released correctly, exceptions and errors are handled, and functionality works correctly across different operating systems and architectures.

        In addition, some unmanaged DLLs may provide managed wrapper DLLs specifically written for managed languages ​​such as C#. These wrapper DLLs provide a more convenient object-oriented API that makes it easier to interact with the unmanaged DLL. In this case, you can reference these managed wrapper DLLs directly without using P/Invoke to call functions in the unmanaged DLL.

        To sum up, you can use the P/Invoke mechanism to access and call functions in unmanaged dynamic link libraries in C#. You can call functions in an unmanaged DLL from C# code by declaring a function signature and using the DllImport attribute to specify the path to the DLL and the function name.    

4. Examples


    1. Simulate pressing the Alt+Tab key

        /// <summary>
        ///
        /// </summary>
        /// <param name="bVk">模拟的键</param>
        /// <param name="bScan">保留参数,0</param>
        /// <param name="dwFlags">按键标志,0按下,2释放</param>
        /// <param name="dwExtraInfo">保留,0用(UIntPtr.Zero)表示</param>
        [DllImport("user32.dll")]
        private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

        private void BtnStart_Click(object sender, EventArgs e)
        {
            keybd_event((byte)Keys.Menu, 0, 0, UIntPtr.Zero);//按下alt
            keybd_event((byte)Keys.Tab, 0, 0, UIntPtr.Zero);//按下tab
            keybd_event((byte)Keys.Menu, 0, 2, UIntPtr.Zero);//松开alt
            keybd_event((byte)Keys.Tab, 0, 2, UIntPtr.Zero);//松开tal
        }


    
    
    2. What is extern?
        extern is used to declare an external method. It is often used to interact with unmanaged code (such as C/C++) in order to call functions in unmanaged code in C#.

        Use the extern keyword to introduce the declaration of an unmanaged function into C# code so that the function can be called in C#. When declaring an external function, you need to use the DllImport attribute to specify the name of the unmanaged library and other relevant information.
    
    
    3. What is the difference between Keys.Menu and Keys.Alt?
        The two are actually one key. When representing a single key, use Keys.Menu; when representing a combination (with Ctrl, Shift), use Keys.Alt, which is regarded as a modifier key.

    
    4. What is UIntPtr?
        UIntPtr is a structure that represents an unsigned integer that is a pointer or handle. It can be used to represent the value of a pointer or handle without caring about the specific platform and the size of the pointer. The size of UIntPtr and the size of pointers are platform dependent. On 32-bit systems, the size of UIntPtr is 4 bytes, and on 64-bit systems, the size of UIntPtr is 8 bytes.

        In an unmanaged DLL, when you need to pass a null pointer or invalid handle, you can use UIntPtr.Zero to express it. UIntPtr.Zero is a static field of type UIntPtr. Its value is 0 and can be used to represent a null pointer or invalid handle.

        In unmanaged code, it is common to use integer types such as int or IntPtr to represent pointers or handles. When you need to pass a null pointer or invalid handle, you can set the integer value to 0. In C#, you can use UIntPtr.Zero to represent a pointer or handle with an integer value of 0.


5. Excel dll reference


    Unmanaged dynamic link libraries cannot be directly referenced, but why can Excel's dll be referenced?

    Unmanaged dynamic link libraries (DLLs) cannot be directly referenced in C# code. C# is a managed language and runs in a managed environment, whereas unmanaged DLLs are written in other programming languages ​​such as C++ and run in an unmanaged environment. To use functions from an unmanaged DLL in C# code, you need to declare external methods using the DllImport attribute and the extern keyword.

    However, there are specific unmanaged DLLs, such as Excel's DLLs (e.g. "Interop.Excel.dll"), which are managed wrappers provided by Microsoft specifically for interacting with Excel. These managed wrapper DLLs are written in C# or other managed languages. They encapsulate the COM interfaces and functionality required to interact with Excel and provide a more convenient object-oriented API for C# developers to use.

    Therefore, when we reference Excel's DLL in a C# project, we are actually referencing these managed wrapper DLLs instead of directly referencing the unmanaged DLL. These managed wrapper DLLs have taken care of the details of interaction with unmanaged DLLs and provide a higher level API that allows us to interact with Excel more easily.

    In summary, although unmanaged DLLs generally need to be accessed and called through the P/Invoke mechanism, some specific unmanaged DLLs, such as Excel's DLL, can provide more convenient API and interaction methods by referencing the managed wrapper DLL. In this way, we can use the functionality provided by these managed wrapper DLLs directly in C# code without having to make manual P/Invoke calls.


    P/Invoke (Platform Invocation Services):
    It is a technology for calling unmanaged code on the .NET platform. It allows .NET applications to call functions in unmanaged code such as C/C++ using the DllImport attribute and related DllImport functions.

    Through P/Invoke, functions in unmanaged dynamic link libraries (DLLs) can be called directly from .NET applications. This is useful for situations where you need to access operating system APIs, hardware drivers, or other native code.


 

Guess you like

Origin blog.csdn.net/dzweather/article/details/132830902