[英]Ctypes linux behavior differs on py2 and py3
While writing a python wrapper for the getmntent linux libc function, there is a strange difference between the behaviour between python 2.x and 3.x for the following code where most of the real work is done by the C library. 在为getmntent linux libc函数编写python包装器时,以下代码的python 2.x和3.x之间的行为存在奇怪的区别,其中大多数实际工作都是由C库完成的。 Since I interface C code with python often, Can anyone explain or correct what is going wrong? 由于我经常将C代码与python进行接口连接,因此谁能解释或纠正出现的问题?
import ctypes
import sys
class mntent(ctypes.Structure):
_fields_ = [("fsname", ctypes.c_char_p),
("dir", ctypes.c_char_p),
("type", ctypes.c_char_p),
("opts", ctypes.c_char_p),
("freq", ctypes.c_int),
("passno", ctypes.c_int)]
def main():
libc = ctypes.cdll.LoadLibrary('libc.so.6')
libc.getmntent.restype = ctypes.POINTER(mntent)
libc.fopen.restype = ctypes.POINTER(ctypes.c_void_p)
fp = libc.fopen('/etc/mtab', 'r')
while True:
mounts = libc.getmntent(fp)
if bool(mounts) == False:
libc.fclose(fp)
break
print("%30s %10s %s"%(mounts.contents.dir, mounts.contents.type, mounts.contents.fsname))
main()
The expected output contains all the mount devices listed with their types and mount points. 预期的输出包含列出的所有安装设备及其类型和安装点。 On python 3.x it gives an empty list. 在python 3.x上,它提供了一个空列表。
在Python 3中,所有字符串都是unicode,但是libc.fopen()
希望简单字节字符串作为其参数:
fp = libc.fopen(b'/etc/mtab', b'r')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.