python - ctypes c_char_p 的不同行为?

标签 python python-2.7 python-3.x ctypes

我对不同版本的 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 function (2.7.7) 被编写为处理 strunicode 字符串。在 Python 3 之前,str 是一个 8 位字符串。 CPython 2.x str 内部使用了一个 C 空终止字符串(即以 \0 终止的字节数组),为此 z_set 可以调用PyString_AS_STRING (即获取指向 str 对象的内部缓冲区的指针)。一个unicode 字符串首先需要被编码成字节串。 z_set 自动处理此编码并在 _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 function (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 是安全的。

关于python - ctypes c_char_p 的不同行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23852311/

相关文章:

python - 删除重复的 Python 循环链表

python-3.x - 在TensorFlow中,函数 'axis'中的参数 'tf.one_hot'是什么

python - 如何将大型数据集加载到 gensim word2vec 模型

Python 列表索引超出拆分返回值的范围

python-2.7 - 了解 Python 中一行中的多个变量赋值

python-3.x - 将数字列表列表转换为数字以逗号分隔的列表列表

python - 无法从 'save_virtual_workbook' 导入名称 'openpyxl.writer.excel'

python - 在 python2.7 上安装 libxml 预构建二进制文件

python - 需要建议在 python 中的 AWS API 中添加指数回退逻辑

Python - 如何使所有按钮每行对齐,看起来像按钮墙