簡體   English   中英

python ctypes 模塊如何將 uint64_t 從 c++func 返回到 python int,未設置 restype=c_long_long

[英]python ctypes module how to transfer uint64_t from c++func return to python int,not set restype=c_long_long

我使用 python ctypes 模塊從 c++ function 計算 crc,它返回 uint64_t 類型。 在 python 中,我沒有設置 restype(c_long_long),我得到一個 python int 值 -870013293,但是設置 restype 的值為 14705237936323208851。你能告訴我關於 int_val 和 long_val 的關系嗎?

以下是文檔中的內容: https://docs.python.org/3/library/ctypes.html#module-ctypes

Python 整數作為平台默認 C int 類型傳遞,它們的值被屏蔽以適應 C 類型。

因此,默認值被視為 c_int,並且:

表示 C signed int 數據類型。 構造函數接受一個可選的 integer 初始化器; 沒有進行溢出檢查。 在 sizeof(int) == sizeof(long) 的平台上,它是 c_long 的別名。

由於沒有溢出並且數字是有符號的,而不是大數字,它可以 output 從 -2,147,483,648 到 2,147,483,647 之間的任何數字。(32 位)

如果您知道返回值將是無符號的並顯式鍵入 c_uint64(通常是 c_ulonglong 的別名),那么您將獲得所需的值。(64 位)

ctypes的默認返回類型是c_int ,它是一個 32 位有符號值。 如果您沒有為 64 位值設置.restype = c_uint64 ,則返回值會錯誤地從 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 位有符號值匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM