Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect result with islower when using ctypes

Tags:

python

c

ctypes

>>> from ctypes import *
>>> import ctypes.util
>>> libc = CDLL("libc.so.6")
>>> libc.printf("%c\n", 104)
h
2
>>> libc.islower(104) # Works fine
512
>>> libc.islower.restype = c_bool # But when i do this...
>>> libc.islower(104)
False
>>> c_bool(512)
c_bool(True)

personally, i think 'h' is lower case..

Is this a bug in ctypes, or am I doing something wrong?

like image 957
LordAro Avatar asked Mar 19 '23 03:03

LordAro


1 Answers

restype is not there just to tell the Python output type, but, most importantly, to tell what is the C type to expect, and thus how to marshal it. islower returns an int, which is typically 4 bytes wide; if you say it returns a bool (which is normally 1 byte) you are breaking the expectations of the marshaling code.

This time you got an incorrect result (probably because on your platform the return code goes in a register, and so it's just taking the lower 8 bits of it), on another platform or for another type this could easily break the stack, and thus crash your process.

So: don't do that. Always respect the C API types and convert after the call.

like image 152
Matteo Italia Avatar answered Apr 01 '23 12:04

Matteo Italia