python - 使用 `sys.getsizeof(Var)` 方法与 `ctypes.sizeof(Var)` 的 python 大小的 ctypes

标签 python size byte ctypes sys

我对 python 中的变量大小有疑问,我使用 Ctypes 因为我想要一个 1 字节的数字,但是当我试图在 python 中检查它的大小时(通过 sys.getsize ) 它说它是 80 字节但是当我检查 ctypes 时(通过 ctypes.sizeof)它说它只有 1 字节,有人能告诉我有什么区别以及为什么有 2 种不同的大小?是因为 python 正在使用对象或包装器吗?当它发送到 c 时它会查看实际大小?

import sys
import ctypes

print("size in ctypes is : ",ctypes.sizeof(ctypes.c_byte(1)))
print("size in sys is : ",sys.getsizeof(ctypes.c_byte(1)))

结果

size in ctypes is :  1
size in sys is :  80

最佳答案

如果你想知道细节,你应该看看objects.h (尤其是文件顶部的注释)。您的 ctypes.c_byte(1) 是一个 Python 对象:

>>> import sys
>>> import ctypes
>>> isinstance(ctypes.c_byte(1), object)
True

如@Daniel 所述,sys.getsizeof 获取该 Python 对象的大小。该 Python 对象大于 C 中的相应对象。请注意 object.h 注释中的以下内容:

Objects are structures allocated on the heap. . . .
The actual memory allocated for an object
contains other data that can only be accessed after casting the pointer
to a pointer to a longer structure type.  This longer type must start
with the reference count and type fields; the macro PyObject_HEAD should be
used for this.

换句话说,宏 PyObject_HEAD 附加到每个对象的开头。这会增加 Python 对象的大小。

另一方面,

ctypes.sizeof 返回 Python 对象中 C 数据类型的实际大小(使用 C 的 sizeof 运算符)。

编辑

根据您在对 Daniel 帖子的评论中提到的目标,可以在 Python 3.x 中通过服务器发送一个字节。下面是一个示例,说明如何使用 Python 的 socket 模块发送一个字节来证明这一点。

这是您将在一个 Python 解释器中运行的服务器:

# Server
import socket

HOST = ''                      # All available interfaces
PORT = 50007                   # Same port as client
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1)        # receive data with bufsize 1; a larger bufsize will break this code
    if not data: break
    conn.sendall(data)
conn.close()

这是客户端,您将在另一个 Python 解释器中运行它:

# Client
import socket

HOST = '127.0.0.1'             # The remote host, but here using localhost
PORT = 50007                   # The port used by both the client and server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'1')                # a bytes object
data = s.recv(1)               # Receive data from the socket with bufsize of 1
s.close()
print('Received', repr(data))  # confirm receipt

关于python - 使用 `sys.getsizeof(Var)` 方法与 `ctypes.sizeof(Var)` 的 python 大小的 ctypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27213647/

相关文章:

python - 如何在调用 dos2unix 以验证 checkin 文件的 SVN 中实现预提交 Hook 脚本

.net - 忽略 .net 中窗口字体大小的增加

matlab - 将图像分成3*3的 block

python-3.x - 为什么我无法使用逻辑运算符和索引获得预期输出?

python - 如何在 python 中从不同的数据类型创建 "byte stream"

java - 字节与字符串之间的奇怪转换

javascript - Python 套接字服务器在收到数据后崩溃

python - 制作具有特定数据格式的 numpy 数组

python - 如何按列 Id 对数据框进行分组,然后在组内标记 2 天的间隔?

检查正确的数组长度是否是 C 中的 malloc