shelper
shelper

Reputation: 10573

Equivalent numpy scripts producing different results

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)

Upvotes: 2

Views: 91

Answers (1)

NPE
NPE

Reputation: 500167

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.

Upvotes: 4

Related Questions