Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用ctypes从缓冲区提取数据_Python_Buffer_Extract_Ctypes - Fatal编程技术网

Python:使用ctypes从缓冲区提取数据

Python:使用ctypes从缓冲区提取数据,python,buffer,extract,ctypes,Python,Buffer,Extract,Ctypes,我能够在Python中成功地使用ctypes调用函数。我现在有了一个缓冲区,它充满了我想要提取的数据结构。这方面的最佳策略是什么?还有什么我应该发的吗 功能: class list(): def __init__(self): #[...] def getdirentries(self, path): self.load_c() self.fd = os.open(path, os.O_RDONLY) self.s

我能够在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

缓冲区:
我想知道为什么您使用os.stat()而不是调用statinfo,使用os.path.walk()而不是调用getdirentries


通常,当您有要传入和传出C的数据缓冲区时,您会使用struct modules pack和unpack方法来完成这项工作

如果我不清楚,缓冲区将包含一些dirent()结构。我可以使用first dirent.d_recen来确定self.buffer中first dirent()结构的大小。我也应该使用self.basep索引通过lseek(3)遍历结构。那么,我如何获取第一个缓冲区条目呢?谢谢我感兴趣的是实际检查目录条目本身,而不是遍历目录。至于os.stat,我使用的是os.fstat,因为FD已经打开了。有没有更好的方法来确定目录项的大小?谢谢“目录大小”是什么意思?您是指用于存储目录数据的字节数、目录中的条目数,还是用于存储目录中所有非目录条目的总字节数?关于最后一个,请参阅以获取一些想法。我不确定它是否可以处理链接,即在类unix系统上具有相同I节点号的两个文件,但对于Windows,这不会是问题。没有更好的方法来获取目录中所有文件的总字节数,除了遍历每个条目并汇总文件大小。用于存储目录数据的字节数。我使用Unpacket和ctypes结构来存储数据(这有点多余,但很好)。很好,谢谢你的建议!