i have a question about ctypes in python
from ctypes import *
printf = cdll.msvcrt.printf
printf("%s\n", "Hello World!")
printf("%d\n", 100)
printf("%f\n", 10.1)
Result:
Hello World!
100
Traceback (most recent call last):
File "C:\Users\Windows7\Desktop\test.py", line 5, in <module>
printf("%f\n", 10.1)
ctypes.ArgumentError: argument 2: <type 'exceptions.TypeError'>: Don't know how to convert parameter 2
I know that how to correct the mistake: 10.1 should be replaced by c_double(10.1), but why should I use c_double() function here? The first two printf doesn’t need c_string() or c_int() at all.
And what’s more, it’s “%f”, not “%lf”, so i think if i must use ctypes function here, i should use c_float() instead of c_double, but when i tried printf("%f", c_float(10.1)), i got the wrong result: 0.000000, why?
Try
printf("%f", c_double(10.1))Explanation:
printf()is a varargs function. The format parameters explain which type you can expect on the stack.The problem: There is no way to distinguish between
floatanddoublearguments when looking at the format butfloatuses 4 bytes whiledoubleuses 8. So how canprintf()tell which one has been pushed on the stack by the code?Answer:
floats are always converted todouble. This way, all floating point types always use the same number of bytes on the stack andprintf()can figure out their address.