unique_ptr | Unique for autoclose handle
Leonardo
leotada523 at gmail.com
Wed Dec 14 13:12:03 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!
If you need an specific shutdown maybe you can use scopes. But
I'm here learning too.
https://tour.dlang.org/tour/en/gems/scope-guards
More information about the Digitalmars-d-learn
mailing list