在python中使用ctypes方法会产生意外错误

Bra*_*tes 8 python ctypes

我对python和ctypes很新.我正在努力完成一项看似简单的任务,但却得到了意想不到的结果.我正在尝试将字符串传递给ac函数,所以我使用的是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
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

San*_*nta 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')
>>>
Run Code Online (Sandbox Code Playgroud)