帮助我理解为什么我琐碎使用Python的ctypes模块失败了

lar*_*sks 5 python malloc ctypes

我试图理解Python"ctypes"模块.我已经把一个简单的例子放在一起 - 理想情况下 - 包装了statvfs()函数调用.代码如下所示:

from ctypes import *

class struct_statvfs (Structure):
    _fields_ = [
            ('f_bsize', c_ulong),
            ('f_frsize', c_ulong),
            ('f_blocks', c_ulong),
            ('f_bfree', c_ulong),
            ('f_bavail', c_ulong),
            ('f_files', c_ulong),
            ('f_ffree', c_ulong),
            ('f_favail', c_ulong),
            ('f_fsid', c_ulong),
            ('f_flag', c_ulong),
            ('f_namemax', c_ulong),
            ]


libc = CDLL('libc.so.6')
libc.statvfs.argtypes = [c_char_p, POINTER(struct_statvfs)]
s = struct_statvfs()

res = libc.statvfs('/etc', byref(s))
print 'return = %d, f_bsize = %d, f_blocks = %d, f_bfree = %d' % (
    res, s.f_bsize, s.f_blocks, s.f_bfree)
Run Code Online (Sandbox Code Playgroud)

运行这个总是返回:

return = 0, f_bsize = 4096, f_blocks = 10079070, f_bfree = 5048834
*** glibc detected *** python: free(): invalid next size (fast): 0x0000000001e51780 ***
*** glibc detected *** python: malloc(): memory corruption (fast): 0x0000000001e517e0 ***
Run Code Online (Sandbox Code Playgroud)

我无法找到任何调用复杂类型作为参数的函数的例子(有许多函数返回复杂类型的例子),但是在盯着ctypes文档一天左右之后我认为我的调用语法是正确...它实际上是调用statvfs()调用并获得正确的结果.

我是否误解了ctypes文档?或者还有其他事情发生在这里?

谢谢!

Mat*_*ner 4

struct statvfs执行此命令以获得系统上的确切定义:

echo '#include <sys/statvfs.h>' | gcc -E - | less
Run Code Online (Sandbox Code Playgroud)

然后按/struct statvfs<enter>跳至定义并从那里浏览。

另请查看我的fusions 补丁及其定义