Python:使用 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.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>

最佳答案

我想知道为什么您使用 os.stat() 而不是调用 statinfo 和 os.path.walk() 而不是调用 getdirentries?

通常,当您有要传入和传出 C 的数据缓冲区时,您会使用 struct modules pack 和 unpack 方法来执行此操作。

关于Python:使用 ctypes 从缓冲区中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578752/

相关文章:

python - Python中自定义命令行解析

python - 类型错误 : invalid type promotion while fitting a logistic regression model in Scikit-learn

c++ - 用 iostream 运算符填充缓冲区

Emacs:如何默认切换 Buffer-menu-files-only

mysql 5.7如何将json数组提取到多列?

python - Tensorflow 在使用 tf.device ('/cpu:0' 时分配 GPU 内存)

python - 使用 Python 的只读二进制平面文件存储选项

Java NIO : reading variable-sized blocks

json - Nifi - 从数组中提取值

python - 如何通过python从一个xml中提取部分到多个xml