4

I am having a funny issue with ctypes; while it seems to work in regular python scripts, when I use it in the interpreter with printf() it prints the length of the string after the string itself. A demo:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> libc = CDLL("libc.so.6") >>> libc.printf("Test") Test4 >>> int = 55 >>> libc.printf("Test %d", int) Test 557 >>> int = c_int(55) >>> libc.printf("Test %d", int) Test 557 

Does anyone know why this happens?

2
  • 2
    Just a note - while int isn't a reserved word, it is in fact a built-in attribute. You shouldn't get in the habit of assigning references to it. Commented Aug 25, 2010 at 18:16
  • I know, but this is just a small interpreter test. Commented Aug 25, 2010 at 18:18

1 Answer 1

8

From the printf(3) man page:

Upon successful return, these functions return the number of characters printed (not including the trailing ’\0’ used to end output to strings).

The python interpreter is displaying the return code of printf() after you call it. Since you don't have a newline \n at the end of your strings the length is getting printed immediately after the printout. Note that this won't happen in a script, only when you use python interactively.

You could hide this with an assignment:

ret = libc.printf("Test\n") 
Sign up to request clarification or add additional context in comments.

2 Comments

Just curious, is it dangerous to pass a python str into a function expecting char*?
Yes, if the function expects to modify the content of the string. Python strings are immutable. ctypes has a create_string_buffer() function to create character arrays that can be modified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.