Python c型字符的不同行为?

Python c型字符的不同行为?,python,python-2.7,python-3.x,ctypes,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

我对不同版本的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
Python 2.7.5(默认,2013年8月25日00:04:04)
[GCC 4.2.1达尔文兼容苹果LLVM 5.0(clang-500.0.68)]
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>c=“你好”
>>>a=ctypes.c\u char\u p(c)
>>>打印(a.value)
你好
Python 3.3.5(默认,2014年3月11日,15:08:59)
[GCC 4.2.1达尔文兼容苹果LLVM 5.0(clang-500.2.79)]
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>c=“你好”
>>>a=ctypes.c\u char\u p(c)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:需要字节或整数地址,而不是str实例
一个工作,而另一个给我一个错误。哪一个是正确的


如果两者都正确,我如何实现与3.3.5中的2.7相同的行为?我想将char指针从python传递到C。

C\u char\u p
\u SimpleCData
的子类,其类型为
\u=z'
\uuuu init\uuuu
方法调用类型的
setfunc
,对于简单类型
'z'
,它是
z\u集

在Python2中,(2.7.7)是用来处理
str
unicode
字符串的。在Python 3之前,
str
是一个8位字符串。CPython 2.x
str
在内部使用以C null结尾的字符串(即由
\0
终止的字节数组),
z_set
可以调用该字符串(即获取指向
str
对象的内部缓冲区的指针)。
unicode
字符串首先需要编码为字节字符串
z_集
自动处理此编码,并在
\u对象
属性中保留对编码字符串的引用

>>> c = u'spam'
>>> a = c_char_p(c)
>>> a._objects
'spam'
>>> type(a._objects)
<type 'str'>
>c=u'spam'
>>>a=c_char_p(c)
>>>a.不动产物体
“垃圾邮件”
>>>类型(a.。_对象)
在Windows上,默认的ctypes字符串编码是
'mbcs'
,错误处理设置为
'ignore'
。在所有其他平台上,默认编码是
'ascii'
,带有
'strict'
错误处理。要修改默认值,请调用。例如,
设置转换模式('utf-8','strict')

在Python3中,(3.4.1)不会自动将
str
(现在是Unicode)转换为
字节。Python3中的范式转变为严格地将字符串与二进制数据分开。ctypes默认转换被删除,函数
set\u conversion\u mode
也被删除。您必须传递
c\u char\p
a
bytes
对象(例如
b'spam'
'spam'.encode('utf-8')
)。在CPython 3.x中,
z_set
调用C-API函数以获取指向
bytes
对象的内部缓冲区的指针


请注意,如果C函数修改字符串,则需要使用来创建
C_char
数组。查找要键入为
const
的参数,以了解在Python 3中使用
c\u char\p

是安全的,即
c=b“hello”
c\u char\u p
实例指向
bytes
对象的私有缓冲区,因此只能将其用于不会修改字符串的
const
参数。@eryksun如果您可以添加它作为答案,并说明它在python3中更改的原因,我很乐意接受它。感谢您的详细回答。总之,调用
ctypes.c\u char\p(my\u string.encode('utf-8'))
使其在Python3.x中工作。