Calling sequence of functions
Question:
from ctypes import cdll
libc = cdll.msvcrt
message = "Hello World!n"
length = libc.printf("Printing by msvcrt: %s", message)
print length
The result of the code above:
33
Printing by msvcrt: Hello World!
Why is the length of the string printed first, rather than the string itself?
Answers:
You have fired up two separate execution threads: one in Python, one in C (I’m oversimplifying). The Python one finished first.
Another way to get this effect is to generate a stack trace (execution error) in Python, just after executing some very simple (fast) code with print statements. The stack trace can get interleaved with the print output.
You need to call msvcr.fflush(None)
after the output of libc.printf()
:
why does printf() from ctypes display in console output after subsequent print() statements
You are using two separate instances of C runtime libraries. msvcrt.dll
and whatever version Python is linked to. My Python 2.7 version uses msvcr90.dll
, which is from Visual Studio 2008.
This means there are two separate instances of the buffered stdout, and in your case Python’s buffered I/O is flushing before the other instance. I could not reproduce the output of your script.
from ctypes import cdll
libc = cdll.msvcrt
message = "Hello World!n"
length = libc.printf("Printing by msvcrt: %s", message)
print length
The result of the code above:
33
Printing by msvcrt: Hello World!
Why is the length of the string printed first, rather than the string itself?
You have fired up two separate execution threads: one in Python, one in C (I’m oversimplifying). The Python one finished first.
Another way to get this effect is to generate a stack trace (execution error) in Python, just after executing some very simple (fast) code with print statements. The stack trace can get interleaved with the print output.
You need to call msvcr.fflush(None)
after the output of libc.printf()
:
why does printf() from ctypes display in console output after subsequent print() statements
You are using two separate instances of C runtime libraries. msvcrt.dll
and whatever version Python is linked to. My Python 2.7 version uses msvcr90.dll
, which is from Visual Studio 2008.
This means there are two separate instances of the buffered stdout, and in your case Python’s buffered I/O is flushing before the other instance. I could not reproduce the output of your script.