views:

485

answers:

1

I am able to successfully call a function with ctypes in Python. I now have a buffer that is filled with Structures of data I want to extract. What is the best strategy for this? Anything else I should post?

Function:

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)  )

    #[...]

Structure:

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) ) ]

Some Output:
Transferred bytes: 156
sizeof buffer: 272
Buffer: <ctypes.c_char_Array_272 object at 0x8c3f0>

+1  A: 

I wonder why you are using os.stat() instead of calling statinfo and os.path.walk() instead of calling getdirentries?

Normally, when you have buffers of data that you want to pass in and out of C, you would use the struct modules pack and unpack methods to do this.

Michael Dillon
I'm interested in actually examining the directory entries themselves versus traversing the directory. As for os.stat, I'm using os.fstat since the FD is already open. Would there be a better way to determine the size of the directory entry?Thanks!
cykyc
What do you mean by "directory size"? Do you mean the number of bytes used to store the directory data, the number of entries in the directory, or the total bytes used for storing all the non-directory entries in the directory? For the last one, see http://code.activestate.com/recipes/86554/ for some ideas. I'm not sure that it handles links OK, i.e. two files with the same i-node number on unix-like systems, but for Windows that would not be an issue. There is no better way to get the total bytes for all files in a directory other than going through each entry and summing up the file sizes.
Michael Dillon
Number of bytes used to store the directory data.
cykyc
I used unpacked and the ctypes structure for storing the data (which was a bit redundant, but oh well). Worked well enough, thanks for the suggestion!
cykyc