Search code examples
pythoncwindowspydev

Python 3.5 ctypes libc printf() only prints first byte of string Windows 7/10


I'm trying to follow one of the Gray Hat Python examples and it works fine in Python 2.7, but in Python 3.5 the result is truncated.

from ctypes import * 

msvcrt = cdll.msvcrt
message_string = "Hello World!\n"
msvcrt.printf("Testing: %s\n", message_string)

You can see below the the output of the code above is just the letter T.

enter image description here

Based one some other posts similar to this one, adding a b to the last line helps but then the message_string is truncated.

from ctypes import * 

msvcrt = cdll.msvcrt
message_string = "Hello World!\n"
msvcrt.printf(b"Testing: %s\n", message_string)

enter image description here

How do I get it to print the entire string stored in the message_string variable, using Python 3.5 on Windows 7 or 10?


Solution

  • Got it to work! Needed to add the b in the variable declaration too. Such a small detail too...See adjusted code below:

    from ctypes import * 
    
    msvcrt = CDLL('msvcrt')
    message_string = b"Hello World!\n"
    msvcrt.printf(b"Testing: %s\n", message_string)
    

    Tested on Windows 7 64bit, w/ Python 3.5, & Windows 10 64bit w/ Python 3.4

    enter image description here

    Gray Hat Python - chapter1-printf.py - example