Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and ctypes: why printf("%f", 10.1) is wrong

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?

like image 534
Searene Avatar asked Apr 01 '26 16:04

Searene


1 Answers

According to the ctypes documentation :

None, integers, longs, byte strings and unicode strings are the only native Python objects that can directly be used as parameters in these function calls. None is passed as a C NULL pointer, byte strings and unicode strings are passed as pointer to the memory block that contains their data (char * or wchar_t *). Python integers and Python longs are passed as the platforms default C int type, their value is masked to fit into the C type.

So, you don't need to use c_int or c_string because those are "native" python objects.

For your second problem, Wikipedia says :

f, F : double in normal (fixed-point) notation. 'f' and 'F' only differs in how the strings for an infinite number or NaN are printed ('inf', 'infinity' and 'nan' for 'f', 'INF', 'INFINITY' and 'NAN' for 'F').

MSDN says too that a "f" modifier is for a double type.

So, it looks like python-ctypes read the same documenation and consider that with a %f you have to give a double.

like image 102
Cédric Julien Avatar answered Apr 08 '26 08:04

Cédric Julien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!