unique_ptr | Unique for autoclose handle

j my.email at gmail.com
Sun Dec 18 04:48:41 UTC 2022


On Wednesday, 14 December 2022 at 11:30:07 UTC, Vitaliy Fadeev 
wrote:
> 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!



The most beautiful way is any high-level language. What you seem 
to lack is developing your engineering skills, something most of 
us begin doing in elementary schooling.


More information about the Digitalmars-d-learn mailing list