Hello all
In my application I have a function that takes a Python object and returns a
struct containing some variation of that object's data. This data is stored
in ctypes arrays. I need a way to ensure that I have references to these
arrays for as long as the struct instance exists.
Specifically, I have these structs:
class node(Structure):
_fields_ = [
('index', c_int),
('value', c_double)
]
class problem (Structure):
_fields_ = [
('l', c_int),
('y', POINTER(c_double)),
('x', POINTER(POINTER(node)))
]
Then I have the following function to create and populate the struct (it
uses the nice ctypes goodies recently added to NumPy):
def create_problem(self, data):
prob = problem()
prob.l = len(data)
y = (c_double* prob.l)()
x = (POINTER(node)* prob.l)()
for i, (yi, xi) in enumerate(data):
y[i] = yi
x[i] = cast(xi.ctypes.data, POINTER(node))
prob.x = cast(addressof(x), POINTER(POINTER(node)))
prob.y = cast(addressof(y), POINTER(c_double))
return prob
While the problem instance exists, I need to keep around references to y and
x so that they aren't deallocated, invaliding the contents of prob.
Will the following do the trick?
prob._x = x
prob._y = y
It seems to work, but I don't know if there might be some caveats.
The other option would be to return prob,y,x from the function and let the
caller make sure that they keep references to y and x around while working
with prob, but this seems like a bit of a hack.
Regards,
Albert
|