[英]Different behaviour of ctypes c_char_p?
我对不同版本的python的这种行为感到困惑,不明白为什么?
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> c="hello"
>>> a=ctypes.c_char_p(c)
>>> print(a.value)
hello
Python 3.3.5 (default, Mar 11 2014, 15:08:59)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> c="hello"
>>> a=ctypes.c_char_p(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bytes or integer address expected instead of str instance
一个工作,而另一个给我一个错误。 哪一个是正确的?
如果它们都是正确的,我怎样才能实现与3.3.5中的2.7相同的行为? 我想将char指针从python传递给C.
c_char_p
是的一个子类_SimpleCData
,与_type_ == 'z'
__init__
方法调用类型的setfunc
,对于简单类型'z'
,它是z_set
。
在Python 2中, z_set
函数 (2.7.7)来处理str
和unicode
字符串。 在Python 3之前, str
是一个8位字符串。 CPython的2.x的str
内部使用一个C空终止字符串(即,由封端的字节数组\\0
),为此z_set
可以调用PyString_AS_STRING
(即获得的指针的内部缓冲器str
对象)。 首先需要将unicode
字符串编码为字节字符串。 z_set
自动处理此编码,并在_objects
属性中保留对编码字符串的_objects
。
>>> c = u'spam'
>>> a = c_char_p(c)
>>> a._objects
'spam'
>>> type(a._objects)
<type 'str'>
在Windows上,默认的ctypes字符串编码为'mbcs'
,错误处理设置为'ignore'
。 在所有其他平台上,默认编码为'ascii'
,错误处理为'strict'
。 要修改默认值,请调用ctypes.set_conversion_mode
。 例如, set_conversion_mode('utf-8', 'strict')
。
在Python 3中, z_set
函数 (3.4.1)不会自动将str
(现在为Unicode)转换为bytes
。 范例在Python 3中转移到严格划分二进制数据中的字符串。 删除了ctypes默认转换,函数set_conversion_mode
。 你必须传递c_char_p
一个bytes
对象(例如b'spam'
或'spam'.encode('utf-8')
)。 在CPython 3.x中, z_set
调用C-API函数PyBytes_AsString
来获取指向bytes
对象的内部缓冲区的指针。
请注意,如果C函数修改了字符串,则需要使用create_string_buffer
来创建c_char
数组。 查找要输入为const
的参数,以便知道使用c_char_p
是安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.