ctypes: printf returns length which is int instead of the string

Question:

I’m using ctypes and loading msvcrt.dll in Python 2.5.

>>> from ctypes import *
>>> libname = 'msvcrt.dll'
>>> libc = CDLL(libname)
>>> libc.printf("Hello Worldn")
12
>>>  

Why doesn’t it print Hello World?

Asked By: user235273

||

Answers:

The C printf() function itself is defined to return the number of characters printed to the output. This is the value that Python receives when you call libc.printf().

The ctypes tutorial provides information on why the output from printf() may not work within your Python REPL (my psychic debugging skills indicate that you’re running the Windows GUI IDLE).

Answered By: Greg Hewgill

Why doesn’t it print Hello World?

It does in my Python (ActiveState, 2.6), when run from the console:

>>> from ctypes import *
>>> libc = CDLL('msvcrt.dll')
>>> libc.printf("Hello worldn")
Hello world
12


(source: typepad.com)

Answered By: David Heffernan

I don’t know how ctypes works in windows systems, but when I was using ubuntu system, I write like this : libc=CDLL(“libc.so.6”)
So ,do you have something wrong with your libs?

Answered By: Bella

For others who came here and couldn’t get this to work on Python 3.x, the reason is that you must pass a bytes string (b"whatever") not a regular python literal string.

So this code works well on my OSX High Sierra:

from ctypes import *

libc = CDLL('/usr/lib/libc.dylib')
libc.printf(b"Testing: hello world")
Answered By: solidak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.