我对不同版本的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相同的行为?我想从Python将char指针传递给C。
bytes
,例如c = b"hello"
。c_char_p
实例指向bytes
对象的私有缓冲区,因此仅在不修改字符串的情况下使用这个实例来处理const
参数。 - Eryk Sun