gpt4 book ai didi

Python 和 ctypes : why printf ("%f", 10.1) 是错误的

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:20 25 4
gpt4 key购买 nike

我有一个关于 python 中的 ctypes 的问题

from ctypes import *
printf = cdll.msvcrt.printf
printf("%s\n", "Hello World!")
printf("%d\n", 100)
printf("%f\n", 10.1)

结果:

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

我知道如何改正错误:10.1应该用c_double(10.1)代替,但为什么要在这里使用c_double()函数呢?前两个 printf 根本不需要 c_string()c_int()

而且,它是“%f”,而不是“%lf”,所以我想如果我必须在这里使用 ctypes 函数,我应该使用 c_float() 而不是 c_double,但是当我尝试 printf("%f", c_float(10.1)),我得到了错误的结果:0.000000,为什么?

最佳答案

根据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.

因此,您不需要使用 c_int 或 c_string,因为它们是“原生”python 对象。

对于你的第二个问题,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 “f”修饰符也适用于 double 类型。

因此,看起来 python-ctypes 读取相同的文档并考虑使用 %f 你必须给出一个双倍。

关于Python 和 ctypes : why printf ("%f", 10.1) 是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8150648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com