【发布时间】:2014-07-14 04:13:14
【问题描述】:
我对不同版本的 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。
【问题讨论】:
-
在 Python 3 中使用
bytes,即c = b"hello"。c_char_p实例指向bytes对象的私有缓冲区,因此仅将其用于不会修改字符串的const参数。 -
标签: python python-2.7 python-3.x ctypes