Reputation:
I was wondering if I had to close the handle if for example I were to call GetModuleHandle
this way
GetProcAddress(GetModuleHandle("modulename"), "nameoftheexportedfunction")
what would be the proper way to close the handle? Do I need to do
HMODULE hModule = GetModuleHandle("modulename");
GetProcAddress(hModule, "nameoftheexportedfunction")
CloseHandle(hModule);
Or does it get deleted automatically if the value returned by GetModuleHandle
isn't stored into a variable?
Upvotes: 3
Views: 3559
Reputation: 36016
The Windows API can be very confusing in this respect, as there are multiple things called a handle, and they all have different rules.
In this case, CloseHandle
closes kernel handles, which typically refer to files or other kernel resources such as synchronization objects that are created with a name—which all are identified by being returned as a HANDLE
.
GetModuleHandle
returns an HMODULE
—actually the base address of a loaded EXE or DLL—and, as it is not a HANDLE
, does not need to be, and must not be, released with CloseHandle
.
As @David Heffernan points out, this does not mean other handle types never have their own destroy/release/un-acquire semantics, and it also does not mean that every HANDLE
you get from an API must be passed to CloseHandle
either. There is just no substitute for knowing the specific API you are dealing with and its particular handle management requirements.
Upvotes: 4
Reputation: 51345
GetModuleHandle returns an HMODULE
(aka HINSTANCE
- see What is the difference between HINSTANCE and HMODULE?). This data type cannot be passed to CloseHandle.
The HMODULE
could be passed to FreeLibrary but that is not required either, since GetModuleHandle
doesn't increase the reference count on the module. In fact, calling FreeLibrary
might cause the module to get unmapped prematurely, leading to a spectacular crash.
In short: GetModuleHandle
returns a read-only value, that doesn't need to be disposed off in any way. The first line of code in your question is fine.
Upvotes: 10