Python:使用ctypes从缓冲区提取数据
我已经成功地在Python中使用ctypes调用了一个函数。现在我有一个缓冲区,里面填充了一些数据结构,我想提取这些数据。请问有什么好的方法吗?还有其他我需要提供的信息吗?
函数:
class list():
def __init__(self):
#[...]
def getdirentries(self, path):
self.load_c()
self.fd = os.open(path, os.O_RDONLY)
self.statinfo = os.fstat(self.fd)
self.buffer = ctypes.create_string_buffer(self.statinfo.st_size)
nbytes = self.statinfo.st_size
transferred_bytes = self.libc.getdirentries(
self.fd,
ctypes.byref(self.buffer),
nbytes,
ctypes.byref(self.basep) )
#[...]
结构:
class dirent(ctypes.Structure):
_fields_ = [ ("d_fileno", ctypes.c_uint32), # /* file number of entry */
("d_reclen", ctypes.c_uint16), # /* length of this record */
("d_type", ctypes.c_uint8), # /* file type */
("d_namlen", ctypes.c_uint8), # /* length of string in d_name */
("d_name", ctypes.c_char * (MAXNAMELEN + 1) ) ]
一些输出:
传输的字节数:156
缓冲区大小:272
缓冲区:<ctypes.c_char_Array_272 object at 0x8c3f0>
1 个回答
0
我想知道你为什么用 os.stat() 而不是直接调用 statinfo,以及为什么用 os.path.walk() 而不是调用 getdirentries?
通常情况下,当你有一些数据需要在 C 语言和其他地方传递时,你会使用 struct 模块的 pack 和 unpack 方法来处理这些数据。