在Python中使用ctypes方法时出现意外错误
我对Python和ctypes还很陌生。现在我想做一件看起来很简单的事情,但却得到了意想不到的结果。我想把一个字符串传递给一个C语言的函数,所以我使用了c_char_p这个类型,但却出现了错误信息。简单来说,事情是这样的:
>>>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
这到底是怎么回事呢?
1 个回答
8
在Python 3.x中,"文本字面量"
实际上是一个unicode对象。你想要使用字节字符串字面量,比如b"字节字符串字面量"
。
>>> 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')
>>>