unique_ptr | Unique for autoclose handle

Vitaliy Fadeev vital.fadeev at gmail.com
Wed Dec 14 13:58:20 UTC 2022


On Wednesday, 14 December 2022 at 11:30:07 UTC, Vitaliy Fadeev 
wrote:
> How to define HANDLE var ?  What to return from procedure? How 
> to call CloseHandle( h ) when variable destroyed?
>
> I was trying **std.typecons.Unique**. But where I must put 
> **CloseHandle( h )** ?
> I was trying **std.typecons.Unique** with custom class 
> **SafeHabdle**

Last try is:

```
struct SafeHandle
{
     Unique!void _safe;
     alias _safe this;

     this( HANDLE h )
     {
         this._safe = h;
     }

     ~this()
     {
         if ( cast(HANDLE)_safe !is null )
         if ( cast(HANDLE)_safe != INVALID_HANDLE_VALUE )
         {
             if ( CloseHandle( cast(HANDLE)_safe ) == 0 )
                 cast(HANDLE)_safe = null;
         }
     }

     ref HANDLE get()
     {
         return cast( HANDLE )_safe;
     }
}

```

and using:

```
SafeHandle open_keyboard_device2( LPCWSTR path, int* error_number 
)
{
    ...
    SafeHandle dev_handle =
         CreateFileW(
             path,
             0,
             FILE_SHARE_READ | FILE_SHARE_WRITE,
             NULL,
             OPEN_EXISTING,
             0,
             NULL
         );

     if ( dev_handle.get() != INVALID_HANDLE_VALUE )
         ...
    ...
}

void processDevice( ... )
{
     auto dev_handle = open_keyboard_device2( path, &err );
     set_keyboard_indicator2( dev_handle, KEYBOARD_CAPS_LOCK_ON );
     ...
}
```

May be good, but testing...


More information about the Digitalmars-d-learn mailing list