Handle is automatically free?

When I call createfileW using windows crate, it returns a handle. At this time, the Handle

impl windows_core::Free for HANDLE {
    #[inline]
    unsafe fn free(&mut self) {
        if !self.is_invalid() {
            windows_targets::link!("kernel32.dll" "system" fn CloseHandle(hobject : *mut core::ffi::c_void) -> i32);
            unsafe {
                CloseHandle(self.0);
            }
        }
    }
}

I'm curious how exactly that Free works.
After creating a handle, I need to call closehandle, but i wonder if rust will automatically free it if there is free.

thanks.

You mean if Free::free is called when a HANDLE instance gets dropped? Then no. The only method that gets automatically called when a value is dropped is its Drop::drop implementation[1] and Handle does not have a Drop implementation. You can call Free::free from your own Drop::drop method though, i.e. by creating a wrapper around HANDLE.


  1. And the drop glue that drops all fields of the type recursively. ↩ī¸Ž

1 Like