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?

Asked By: Gray

||

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.

Answered By: Prune

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.

Answered By: Mark Tolonen
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.