2009-09-08 107 views
1

我讀ctypes的教程,我碰到這個傳來:ctypes的指針問題

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

,但我不得不使用指針像這樣被:

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' 

爲什麼,當我這樣做一種方式,我可以訪問c_s.value,而當我以另一種方式執行操作時,沒有值對象?

謝謝大家!

回答

3

在你的第二個例子,你有陳述:

c_s = c_char_p() 
c_s = s 

的​​模塊不能打破rules of Python assignments,並在上述情況下,第二分配從剛剛重新綁定c_s名創建的c_char_p對象爲s對象。實際上,這會拋棄新創建的c_char_p對象,並且您的代碼會在您的問題中產生錯誤,因爲常規Python字符串不具有.value屬性。

嘗試,而不是:

c_s = c_char_p() 
c_s.value = s 

,看看是否與你的期望一致。

+0

哦。哇,這是一個偉大的基本答案。謝謝! – trayres 2009-09-11 04:40:47