开发者

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

开发者 https://www.devze.com 2023-02-10 11:02 出处:网络
I\'m using ctypes and loading msvcrt.dll in Python 2.5. >>> from ctypes import * >>> libname = \'msvcrt.dll\'

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

>>> from ctypes import *
>>> libname = 'msvcrt.dll'
>>> libc = CDLL(libname)
>&开发者_开发知识库gt;> libc.printf("Hello World\n")
12
>>>  

Why doesn't it print Hello World?


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 world\n")
Hello world
12


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).


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")


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号