0

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.