Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ctypes methods in python gives unexpected error

Tags:

python

ctypes

I'm pretty new to python and ctypes. I'm trying to accomplish a seemingly easy task but am getting unexpected results. I'm trying to pass a string to a c function so I'm using the c_char_p type but it's giving me an error message. To simply it, this is whats happening:

>>>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

What's going on here?

like image 575
Brandon Yates Avatar asked Dec 12 '11 20:12

Brandon Yates


1 Answers

In Python 3.x, the "text literal" is really a unicode object. You want to use the byte-string literal like 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')
>>>
like image 194
Santa Avatar answered Nov 06 '22 19:11

Santa