[AstroPy] strange error with ctypes

Jerome Caron jerome_caron_astro at ymail.com
Thu Feb 16 05:10:50 EST 2012

Dear list,
I am developping since 2 years a library for photometry in Python. Everything is here: www.aspylib.com
At the moment I have a very strange bug and no idea how to solve it, so I am asking for some help... or recommendations about a better place to ask for help (a different list ?)
My OS is Windows XP. The Python script is calling a few dll (written in C++) that are interfaced with ctypes. 
Looking at the messages in the Python console the error occurs when calling one of these dll (this particular dll is called several hundreds of thousands of times without error just before, and this time there is an error..). The error message is something like:
File "C:\Documents and Settings\jerome caron\My Documents\Python2\aspylib\astro\transform.py", line 35, in translate_Bspline
WindowsError: exception: access violation reading 0x4158B870
The Python code that calls the dll is (I changed it many time without resolving the error)
if len(images.shape)==2:
  dim = 1
  dim_x, dim_y = images.shape
  dim, dim_x, dim_y = images.shape    
indata = np.ascontiguousarray(np.array(images, dtype = np.float32))
dxy = np.ascontiguousarray(np.array(shift, dtype = np.float32))
outdata = np.ascontiguousarray(np.empty(images.shape, dtype = np.float32))
cdll.Bspline.Translate.argtypes = [c_long, c_long, c_long, ndpointer(dtype=np.float32), ndpointer(dtype=np.float32), c_long, ndpointer(dtype=np.float32)]

The dll prototype in C is
int Translate(int dim, int dim_x, int dim_y, float* a, float* shifts, int spline_degree, float* b);
So everything looks ok and I would suspect an error in the C++ code. But here comes the nasty thing.
The code in the dll is very basic and clean. Actually it does not throw any exception as I checked by inserting a try..catch statement
try{ all the dll code here} catch(...){printf("there was an error ni the dll!");}
Investigating further, the error occurs when executing a free() instruction. I don't see how this could create an error ! The piece of C code looks like
 Line = (double *)malloc((size_t)(Width * (long)sizeof(double)));
 if (Line == (double *)NULL) {
  printf("Row allocation failed\n");
    for (y = 0L; y < Height; y++) {
        GetRow(Image, y, Line, Width);
        ConvertToInterpolationCoefficients(Line, Width, Pole, NbPoles, DBL_EPSILON);
        PutRow(Image, y, Line, Width);
And the error occurs at the statement free(Line).
I am starting to suspect something nasty happening with ctypes. Or maybe I am missing something very basic ? Any suggestion ? I am sure there are experienced programmers on this list, who could advice me.
Many thanks for your help and patience reading me
Kind regards
Jerome Caron
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/astropy/attachments/20120216/da69b2b5/attachment.html>

More information about the AstroPy mailing list