[ctypes-users] Reference variables as callback function parameters
Brought to you by:
theller
|
From: James D. <ja...@NB...> - 2008-02-18 11:47:56
|
Hi all, I have a generic problem regarding C functions called from within callbacks, and their reference variables. So I'm wrapping the sundials library, and have written a python class that makes the underlying C structure (the NVector) act like a list in python. In the callback functions it is often necessary to modify the contents of a nvector (the pointer to which is passed into the callback function). So far so good, and easily done as the __getitem__ and __setitem__ methods can modify the contents of the pointed to underlying C structure with ease, as long as we are modifying individual elements of the vectors. Assume, for example, we have a simple callback function for one of the integrators/solvers, which takes time (a float), y (the current vector), and ydot (the resultant vector). Ideally we would like to express this function along the lines of ydot = y*M Where M is some transformation matrix. Of course this doesn't work, because python creates an entirely new variable for ydot in this case, and doesn't modify the contents of memory initially pointed to by ydot. This problem is particularly highlights when we have a C function designed to perform an operation on two vectors, for example scaling. This function scales a source vector by a given floating point scalar, and stores the result in the given destination vector. N_VScale(2.5, src_vector, dst_vectpr) However, the NVector class I have written implements scaling as such src_vector*2.5 Expressing the C in python, I would want dst_vector = src_vector*2.5 But, the * operator on my nvector class instantiates a new NVector, meaning dst_vector now no longer points to the memory contents the calling C function expects modified. I'm trying to think of a way around this, so that the syntax remains clear and consistent for python users, as opposed to some operations on NVectors requiring an explicit function call, whereas others use the expected 'mathematical' notation. It would be really great if I could overload the assignment operator for NVectors, but AFAIK in python this is impossible. Suggestions here would be welcome... Thanks James |