[issue35326] ctypes cast and from_address cause crash on Windows 10

Eryk Sun report at bugs.python.org
Tue Nov 27 12:11:07 EST 2018


Eryk Sun <eryksun at gmail.com> added the comment:

The default function result type is c_int, which truncates a 64-bit pointer to 32-bit. The attribute that needs to be set is singular restype, not plural restypes. Unfortunately ctypes objects have a dict, so you're not catching the typo in an obvious way.

Additional comments:

POINTER(c_ubyte).from_address(ptr) is not the same as cast(ptr, POINTER(c_ubyte)). The first one wrongly instantiates a pointer from the value at the ptr address instead of the address itself. If you want to use from_address, where ptr is a Python integer, a correct expression for this is POINTER(c_ubyte)(c_ubyte.from_address(ptr)).

I recommend using kernel32 = WinDLL('kernel32', use_last_error=True) instead of windll. This allows using ctypes.get_last_error() instead of kernel32.GetLastError(), which is especially more reliable when working in the REPL. It also avoids the problem with cached libraries on the global windll object, which can lead to prototype conflicts between libraries (e.g. if a script makes use of your library and another that uses the Windows API via ctypes, such as colorama), since libraries in turn cache function pointers.

----------
nosy: +eryksun
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35326>
_______________________________________


More information about the Python-bugs-list mailing list