Skip to content

Make optional SafeHandle parameters accept null #129

Closed

Description

While the .NET interop layer may not permit null for SafeHandle parameters, we can certainly support it by making the extern method private and exposing a wrapper to it that checks for null SafeHandle args and does the right thing.

Example:

[DllImport(Entrypoint = "CreateFileW")]
private static extern SafeFileHandle CreateFile_Private(char* path, [Optional, In] SafeHandle hTemplate);

internal static SafeFileHandle CreateFile(char* path, SafeHandle? hTemplate)
{
   return CreateFile_Private(path, hTemplate ?? NullSafeHandle.NullHandle);
}

Activity

  1. jnm2 commented on Feb 18, 2021

    @jnm2
    Contributor

    When the project langversion is >= 8, could you also put #nullable enable or at least #nullable annotations in the file or around the parameter declaration and use SafeHandle? as the parameter type so that IntelliSense shows me that nulls are anticipated?

  2. AArnott commented on Feb 18, 2021

    @AArnott
    MemberAuthor

    Joseph Musser (@jnm2) yes, I have that in mind to eventually do. I filed an issue to track.

  3. added a commit that references this issue on Feb 23, 2021
    23e317c
  4. added a commit that references this issue on May 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions