2011-12-12 77 views
8

我很新的python和ctypes。我试图完成一个看起来很容易的任务,但会得到意想不到的结果。我试图将一个字符串传递给一个c函数,所以我使用c_char_p类型,但它给了我一个错误消息。简而言之,这就是发生了什么:在python中使用ctypes方法给出了意想不到的错误

>>>from ctypes import * 
>>>c_char_p("hello world") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: string or integer address expected instead of str instance 

这是怎么回事?

回答

8

在Python 3.x中,"text literal"确实是一个unicode对象。你想使用字节字符串像b"byte-string literal"

>>> from ctypes import * 
>>> c_char_p('hello world') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: string or integer address expected instead of str instance 
>>> c_char_p(b'hello world') 
c_char_p(b'hello world') 
>>> 
+0

非常感谢你的帮助。原来我在看python 2.7文档,这就是为什么我很困惑。 –

相关问题