[issue30286] ctypes FreeLibrary fails on Windows 64-bit

Eryk Sun report at bugs.python.org
Fri May 5 22:48:30 EDT 2017


Eryk Sun added the comment:

It's documented that the default conversion for integer arguments is a 32-bit C int, which is also the default for result types. Whenever pointers (and Windows handles, which are sometimes 64-bit pointers, such as HMODULE values) are passed as arguments, integer values either need to be manually wrapped as ctypes pointer instances, or you need to set the function's argtypes to override the default behavior. Whenever a pointer is returned, you must set the function's restype.

BTW, _ctypes.FreeLibrary and _ctypes.dlclose already exist as built-in functions. They're just not imported to the main ctypes namespace, most likely because there's nothing in the design to prevent crashing Python if the shared library's reference count drops to 0 and the loader unmaps it from the process while there's remaining references to its address range. 

Also, I recommend using ctypes.WinDLL and avoiding ctypes.windll, especially for common Windows APIs. It caches libraries, which cache function pointer instances. What if my library also uses it and customizes FreeLibrary.argtypes or FreeLibrary.errcheck in a way that breaks yours? It also doesn't allow setting use_last_error=True to capture the last error value in a thread-local variable that can be accessed via ctypes.get_last_error() and ctypes.set_last_error(). Capturing the last error value is a good idea in a high-level language like Python -- especially when working interactively in the REPL. This way ctypes.WinError(ctypes.get_last_error()) will reliable create an exception for whatever the error value was for the last FFI call.

----------
nosy: +eryksun

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30286>
_______________________________________


More information about the Python-bugs-list mailing list