2

I ran the following scripts which is considered as same, but the output is completely different, can anyone explain why?

I first imported the necessary modules:

from ctypes import * import numpy as np 

Code1:

AOVoltage = np.linspace(-1, 1, 2200) AOVoltage = AOVoltage.ctypes.data_as(POINTER(c_double)) print AOVoltage.contents c_double(1.821347161578237e-284) 

Code2:

a = np.linspace(-1, 1, 2200) AOVoltage = a.ctypes.data_as(POINTER(c_double)) print AOVoltage.contents c_double(-1.0) 

Code3:

AOVoltage = (np.linspace(-1, 1, 2200)).ctypes.data_as(POINTER(c_double)) print AOVoltage.contents c_double(1.821347161578237e-284) 
2
  • 1
    I get exactly c_double(-1.0) for each of your Code. Commented Nov 20, 2012 at 15:47
  • 1
    That's interesting. I can't reproduce it from IPython, but I can from the Python prompt, which seems reasonable if the array gets garbage collected in the Python interpreter and the memory that used to hold the array later has something else, but IPython keeps a reference to every input line. Commented Nov 20, 2012 at 17:02

1 Answer 1

4

For this to work, you need to retain a reference to the original numpy array to prevent it from being garbage collected. This is why #2 works, and #1 and #3 don't (their behaviour is undefined).

This is explained in the documentation:

Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer to memory that is invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to the array until ct is deleted or re-assigned.

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

3 Comments

it sounds to be the reason, now i just wonder would it be considered as a bug of the reference counting mechanism of python? or they intentionally make it work this way?
@shelper: It turns out this is documented behaviour. See the updated answer.
ok, this was a tricky one. I didn't know this about ctypes. learnt something. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.