unique_ptr | Unique for autoclose handle

Vitaliy Fadeev vital.fadeev at gmail.com
Wed Dec 14 11:30:07 UTC 2022


Hi! I open a device under Windows:

```
HANDLE h = CreateFileW( ... );
```

in procedure:

```
HANDLE open_keyboard_device2( LPCWSTR path, int* error_number )
{
    ...

     HANDLE dev_handle =
             CreateFileW(
                 path,
                 0,
                 FILE_SHARE_READ | FILE_SHARE_WRITE,
                 NULL,
                 OPEN_EXISTING,
                 0,
                 NULL
             );

     ...

     return dev_handle;
}
```

and I want to close HANDLE automatically, when **dev_handle** 
destroyed by GC:

```
CloseHandle( h );
```

How to do it?
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**
```
class SafeHandle
{
     HANDLE h;

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

     ~this()
     {
         if ( h != INVALID_HANDLE_VALUE )
             CloseHandle( h );
     }
}
```

and using it:
```
Unique!SafeHandle open_keyboard_device2( LPCWSTR path, int* 
error_number )
{
     ...
     Unique!SafeHandle dev_handle =
         new SafeHandle(
             CreateFileW(
                 path,
                 0,
                 FILE_SHARE_READ | FILE_SHARE_WRITE,
                 NULL,
                 OPEN_EXISTING,
                 0,
                 NULL
             )
         );
     ...
}
```
It complex. Because needed:
```
     Unique!SafeHandle open_keyboard_device2( LPCWSTR path, int* 
error_number )
     Unique!SafeHandle dev_handle = new SafeHandle( CreateFileW( 
... ) );
     DeviceIoControl( dev_handle.h, ...);
```
vs
```
     HANDLE open_keyboard_device2( LPCWSTR path, int* error_number 
)
     HANDLE dev_handle = CreateFileW( ... );
     DeviceIoControl( dev_handle, ...);
```

Last is readable.

Teach me the most beautiful way.
How to make beautiful?
Thanks!



More information about the Digitalmars-d-learn mailing list