Re: ctype C library call always returns 0 with Python3

Discussion in 'Python' started by Nobody, May 19, 2012.

  1. Nobody

    Nobody Guest

    On Sat, 19 May 2012 11:30:46 +0200, Johannes Bauer wrote:

    > import ctypes
    > libc = ctypes.cdll.LoadLibrary("/lib64/libc-2.14.1.so")
    > print(libc.strchr("abcdef", ord("d")))


    In 3.x, a string will be passed as a wchar_t*, not a char*. IOW, the
    memory pointed to by the first argument to strchr() will consist mostly of
    NUL bytes.

    Either use a "bytes" instead of a string:

    > print(libc.strchr(b"abcdef", ord("d")))

    1984444291

    or specify the argument types to force a conversion:

    > libc.strchr.argtypes = [c_char_p, c_int]
    > print(libc.strchr("abcdef", ord("d")))

    1984755787
     
    Nobody, May 19, 2012
    #1
    1. Advertising

  2. Nobody

    Hans Mulder Guest

    On 19/05/12 13:20:24, Nobody wrote:
    > On Sat, 19 May 2012 11:30:46 +0200, Johannes Bauer wrote:
    >
    >> import ctypes
    >> libc = ctypes.cdll.LoadLibrary("/lib64/libc-2.14.1.so")
    >> print(libc.strchr("abcdef", ord("d")))

    >
    > In 3.x, a string will be passed as a wchar_t*, not a char*. IOW, the
    > memory pointed to by the first argument to strchr() will consist mostly of
    > NUL bytes.
    >
    > Either use a "bytes" instead of a string:
    >
    > > print(libc.strchr(b"abcdef", ord("d")))
    > 1984444291
    >
    > or specify the argument types to force a conversion:
    >
    > > libc.strchr.argtypes = [c_char_p, c_int]
    > > print(libc.strchr("abcdef", ord("d")))
    > 1984755787


    You'll also want to specify the return type:

    >>> libc.strchr.argtypes = [c_char_p, c_int]
    >>> print(libc.strchr(b"abcdef", ord("d")))

    7224211
    >>> libc.strchr.restype = c_char_p
    >>> print(libc.strchr(b"abcdef", ord("d")))

    b'def'

    Hope this helps,

    -- HansM
     
    Hans Mulder, May 19, 2012
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jon Davis
    Replies:
    1
    Views:
    405
    Jon Davis
    Jan 27, 2004
  2. Jon Davis
    Replies:
    3
    Views:
    500
    Jon Davis
    Jan 27, 2004
  3. legard_new
    Replies:
    2
    Views:
    746
    legard_new
    Aug 1, 2010
  4. FindSun
    Replies:
    0
    Views:
    99
    FindSun
    Apr 16, 2007
  5. Andrew Berg
    Replies:
    0
    Views:
    347
    Andrew Berg
    Jun 16, 2012
Loading...

Share This Page