ctype C library call always returns 0 with Python3

Colin McPhail colin.mcphail at talktalk.net
Sat May 19 07:07:28 EDT 2012


On 19/05/2012 10:30, Johannes Bauer wrote:
> Even the example in the standard library fails:
>
> import ctypes
> libc = ctypes.cdll.LoadLibrary("/lib64/libc-2.14.1.so")
> print(libc.strchr("abcdef", ord("d")))
>
> Always returns "0".

I think there may be two problems with this code:

(1) You are using a 64-bit system but, in the absence of a function 
prototype for strchr, ctypes will be passing and returning 32-bit types. 
To add prototype information put something like:
   libc.strchr.restype = ctypes.c_char_p
   libc.strchr.argtypes = [ctypes.c_char_p, c_int]
before the call of strchr().

(2) In Python3 strings are not plain sequences of bytes by default. In 
your example try passing b"abcdef" instead of "abcdef".

-- CMcP




More information about the Python-list mailing list