我有一个关于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对象的大小。
另一方面,返回python对象中ctypes.sizeof数据类型的实际大小(使用c的C运算符)。
编辑
鉴于您在对daniel文章的评论中提到的目标,可以在python 3.x中通过服务器发送一个字节。下面是一个示例,说明如何使用python的sizeof模块发送一个字节来证明这一点。
这是服务器,您将在一个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)方法的python大小的ctypes与`ctypes.sizeof(Var)`,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27213647/

10-12 16:38
查看更多