Last error wrongly set by some modules #2302
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a proposed fix for #2301.
When searching for functions in libraries, GetModuleHandle is attempted 1st (most likely to avoid incrementing RefCount), and only if it fails LoadLibrary is used. Unfortunately, for libraries that aren't already loaded ("secur32* for win32api or msimg32 for win32gui) GetModuleHandle sets last error flag to 126: ERROR_MOD_NOT_FOUND. Since the flag is not cleared, for win32gui my EnumWindows changes seem to have no effect.
The proposed fix is in a form of a macro that does the library loading (following Py_BEGIN_ALLOW_THREADS model) and clears this particular error.
Notes:
A simpler way would be to simply clear the error once (just before module initialization end), but that's lame, and may swallow other errors that could come and bite in the ass at a later time (just like this one did)
I only fixed these 2 modules (as a POC). I will fix the others affected (a quick code search revealed them), once I have the green light, as this is basically monkey-work (that I don't want to do more than absolutely necessary)
My win32gui tests were not affected by it since I'm manually clearing the error flag. I remember that I ran into this error at the time, and clearing the flag fixed the problem which was good enough (I didn't dig deeper). But tests are perfectly fine, as they should start from a known (and deterministic) state
I don't know why this method with function pointers was chosen (instead of linking with the .lib files), as a vast majority of these functions are there since Windows 2000 (and exposed by VStudio)
I wouldn't be surprised if there were more open issues caused by this