Python CTYPES模块如何从C++ func返回python int,而不设置restype = c_long_long

发布于 2025-01-25 08:55:11 字数 172 浏览 4 评论 0 原文

我使用python ctypes模块从C ++函数中返回uint64_t类型。 在Python中,我没有设置Restype(C_LONG_LONG),我获得了一个python int值-870013293,但是设置Restype值为1470523793632320851。 您能告诉我有关int_val和long_val的关系吗?

i use python ctypes module to cal crc from c++ function it return uint64_t type.
In python, i do not set restype(c_long_long), i get a python int value -870013293 , however set restype the value is 14705237936323208851.
can you tell me the relation about int_val and long_val.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这样的小城市 2025-02-01 08:55:11

ctypes 的默认返回类型是 c_int ,它是一个32位签名的值。如果您不设置 .restype = C_UINT64 为64位值,则返回值将从C不正确地转换为c转换为Python。如果您以十六进制显示,则可以看到该值将其截断为32位:

>>> hex(-870013293 & 0xFFFFFFFF)  # twos complement representation of a 32-bit negative value
'0xcc24a693'
>>> hex(14705237936323208851)     # the actual return value
'0xcc137ffdcc24a693'

请注意,64位值的最后32位与32位签名的值匹配。

The default return type for ctypes is c_int which is a 32-bit signed value. If you don't set .restype = c_uint64 for a 64-bit value, the return value is converted incorrectly from C to Python. You can see that the value was truncated to 32 bits if you display it in hexadecimal:

>>> hex(-870013293 & 0xFFFFFFFF)  # twos complement representation of a 32-bit negative value
'0xcc24a693'
>>> hex(14705237936323208851)     # the actual return value
'0xcc137ffdcc24a693'

Note that the last 32 bits of the 64-bit value match the 32-bit signed value.

临风闻羌笛 2025-02-01 08:55:11

这是文档中写的内容: https> https://docs.python .org/3/library/ctypes.html#module-ctypes

python整数作为默认的c int类型传递,它们的值被掩盖以适合C类型。

因此,默认值将值视为C_INT,并且:

表示C签名的INT数据类型。构造函数接受可选的整数初始化器;未完成溢出检查。在sizeof(int)== sizeof(long)的平台上,这是c_long的别名。

由于没有溢出并且数字签名,而不是大数字,因此可以输出任何数字,从-2,147,483,648到2,147,483,647

。 c_ulonglong),然后您将获得所需的价值。(64位)

Here is what is written in the documentation: https://docs.python.org/3/library/ctypes.html#module-ctypes

Python integers are passed as the platforms default C int type, their value is masked to fit into the C type.

Therefore, default the value is treated as c_int, and:

Represents the C signed int datatype. The constructor accepts an optional integer initializer; no overflow checking is done. On platforms where sizeof(int) == sizeof(long) it is an alias to c_long.

Since there is no overflow and the number is signed, instead of a large number, it can output any number from -2,147,483,648 to 2,147,483,647.(32 bits)

If you know the return value will be unsigned and explicitly type c_uint64 ( usually an alias for c_ulonglong), then you'll get the value you want.(64 bits)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文