views:

175

answers:

1

Hi everyone - I was reading the ctypes tutorial, and I came across this:

s = "Hello, World"
c_s = c_char_p(s)
print c_s
c_s.value = "Hi, there"

But I had been using pointers like this:

s = "Hello, World!"
c_s = c_char_p()
c_s = s
print c_s
c_s.value

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    c_s.value
AttributeError: 'str' object has no attribute 'value'

Why is it that when I do it one way, I can access c_s.value, and when I do it the other way, there is no value object?

Thanks all!

+3  A: 

In your second example, you've got the statements:

c_s = c_char_p()
c_s = s

The ctypes module can't break the rules of Python assignments, and in the above case the second assignment rebinds the c_s name from the just-created c_char_p object to the s object. In effect, this throws away the newly created c_char_p object, and your code produces the error in your question because a regular Python string doesn't have a .value property.

Try instead:

c_s = c_char_p()
c_s.value = s

and see whether that aligns with your expectations.

Greg Hewgill
Ohh. Wow, that's a great fundamental answer. Thanks!
trayres