Comparison of several methods of CSharp calling Win32 API

Time:2021-10-18

The dllimport tag is the most commonly used DLL in CSharp.
I initially called the methods in user32 and shell32 of the system in the same way, but this requires various definition structures of the imported functions by handwriting. The more reliable method is to directly copy and paste the ready-made ones written by others on the network, or go to pinvoke.net to read the required interface definitions. This website also has a plug-in that can be installed in VS, which is faster.
In addition to manually importing DLLs, nuget already has ready-made encapsulation.

  1. vanipa.PInvoke
    This library is maintained by a third party. It is relatively comprehensive for manual maintenance. There are all functions that can basically deal with all situations.
  2. dotnet/Pinvoke
    This is maintained by Microsoft employees. It is the same as the above, but many function APIs are missing. As of May 21, the project has not changed much in a year or two, and even some APIs in the issue requesting to add foundation have not been managed. The owner’s center of gravity went to cswin32
  3. CsWin32
    This is the CSharp version of the Win32 metadata project, which was developed in the past year and is officially maintained to replace Pinvoke. The API is automatically imported by generating CSharp code from Win32 documents, so that there will be no missing function above, and there will be no redundant dependency on what needs to be imported. However, it is likely that the code with the pointer unsafe will be generated. It is necessary to manually write some functions with the unsafe keyword. Unlike the above processing, you can directly use CSharp’s ref or out syntax to pass parameters and obtain some parameters. Second, the code is generated in the microsoft.windows.sdk namespace. Other ides such as rider will not recognize this namespace, but it can run. Only vs can be used (I don’t know if vscode can be used), which is still very annoying

At this point in time, the three nuget packages are the first, which is more reliable

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]