P/Invoke C# Libraries

repository·main·Indexed 24 days ago

https://github.com/dotnet/pinvoke

A collection of C# libraries providing verified P/Invoke method signatures for popular Windows operating system DLLs. It utilizes SafeHandle-derived types and enums to provide a higher-level API than raw IntPtr and uint flags. Note: This repository is no longer maintained; CsWin32 is the preferred alternative.

Tokens
587
Snippets
3
Records
6
Agent score
30%

What's inside dotnet-pinvoke

  1. Use custom uint values with P/Invoke enums

    main
    If you need to pass a uint value that is not explicitly defined in the provided enum, you can cast the uint directly to the specific enum type required by the method parameter.
  2. Consume P/Invoke packages from the CI feed

    main

    If a P/Invoke signature is available in the source code but has not yet been released to NuGet.org, you can consume it directly from the project's CI feed. Add the following package source to your nuget.config file.

    <add key="PInvoke" value="https://pkgs.dev.azure.com/andrewarnott/OSS/_packaging/PublicCI/nuget/v3/index.json" />
  3. Use P/Invoke method signatures in C#

    main

    Once a package is installed, import the PInvoke namespace. For C# 6 and later, you can use using static to call native methods directly by their name.

    If you are using C# 5, you must call the methods through the library class (e.g., BCrypt.MethodName).

    using PInvoke;
    using static PInvoke.BCrypt; // Supported in C# 6 (VS2015) and later.
    
    // C# 6 syntax
    var error = BCryptOpenAlgorithm(AlgorithmIdentifiers.BCRYPT_SHA256_ALGORITHM);
    
    // C# 5 syntax
    var error = BCrypt.BCryptOpenAlgorithm(BCrypt.AlgorithmIdentifiers.BCRYPT_SHA256_ALGORITHM);
  4. Install P/Invoke libraries via NuGet

    main

    To use P/Invoke signatures for specific Windows DLLs, install the corresponding NuGet package for the library you want to access.

    Note: This repository is no longer maintained. For a new, preferred approach for Win32 P/Invokes in C#, consider using CsWin32.

    Install-Package PInvoke.BCrypt
  5. Resolve ambiguity with null in P/Invoke overloads

    main
    Some P/Invoke methods have multiple overloads, such as those accepting struct* (native pointers) and struct? (nullable structs). Passing null can cause compiler ambiguity errors. To resolve this, explicitly cast the null value to the expected nullable type: (struct?)null.