/[thuban]/branches/WIP-pyshapelib-bramz/libraries/pyshapelib/shapelibmodule.c
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/libraries/pyshapelib/shapelibmodule.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/thuban/libraries/pyshapelib/shapelib.i revision 2637 by bh, Thu Jun 30 14:20:46 2005 UTC branches/WIP-pyshapelib-bramz/libraries/pyshapelib/shapelibmodule.c revision 2742 by bramz, Wed Mar 14 16:26:14 2007 UTC
# Line 1  Line 1 
1  /* SWIG (www.swig.org) interface file for shapelib  #include "pyshapelib_common.h"
  *  
  * At the moment (Dec 2000) this file is only useful to generate Python  
  * bindings. Invoke swig as follows:  
  *  
  *      swig -python -shadow shapelib.i  
  *  
  * to generate shapelib_wrap.c and shapelib.py. shapelib_wrap.c  
  * defines a bunch of Python-functions that wrap the appripriate  
  * shapelib functions and shapelib.py contains an object oriented  
  * wrapper around shapelib_wrap.c.  
  *  
  * Shapelib, and hence this module too, defines two types of objects,  
  * shapes and shapefiles.  
  */  
2    
3  %module shapelib  /* --- SHPObject ----------------------------------------------------------------------------------------------------- */
4    
5  /*  typedef struct
6   * First, a %{,%}-Block. These blocks are copied verbatim to the  {
7   * shapelib_wrap.c file and are not parsed by SWIG. This is the place to          PyObject_HEAD
8   * import headerfiles and define helper-functions that are needed by the          SHPObject* shpObject;
9   * automatically generated wrappers.  }
10   */  SHPObjectObject;
11    
12  %{  /* allocator
13     */
14    static PyObject* shpobject_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
15    {
16            SHPObjectObject* self;  
17            self = (SHPObjectObject*) type->tp_alloc(type, 0);
18            self->shpObject = NULL;
19            return (PyObject*) self;
20    }
21    
22  /* import the shapelib headefile. */  /* deallocator
 #include "shapefil.h"  
 #include "pyshapelib_api.h"  
       
 /*  
  * Rename a few shapelib functions that are effectively methods with  
  * preprocessor macros so that they have the names that swig expects  
  * (e.g. the destructor of SHPObject has to be called delete_SHPObject)  
23   */   */
24    static void shpobject_dealloc(SHPObjectObject* self)
25    {
26            SHPDestroyObject(self->shpObject);
27            self->shpObject = NULL;
28            self->ob_type->tp_free((PyObject*)self);
29    }
30    
31    /* The constructor of SHPObject. parts is a list of lists of tuples
32    * describing the parts and their vertices just likethe output of the
33    * vertices() method. part_type_list is the list of part-types and may
34    * be NULL. For the meaning of the part-types and their default value
35    * see the Shaplib documentation.
36    */
37    static int shpobject_init(SHPObjectObject* self, PyObject* args, PyObject* kwds)
38    {
39            int type;
40            int id;
41            PyObject* parts = NULL;
42            PyObject* part_type_list = NULL;
43            
44            int num_parts;
45            int num_vertices;
46            int part_start;
47            
48            double* xs = NULL;
49            double* ys = NULL;
50            int* part_starts = NULL;
51            int* part_types = NULL;
52            
53            int i;
54            int return_code = -1;
55            
56            /* first, unpack parameters */
57            if (kwds != NULL && PyDict_Size(kwds) > 0)
58            {
59                    PyErr_Format(PyExc_TypeError, "shapelib.SHPObject.__init__ takes no keyword arguments");
60                    return -1;
61            }
62            if (!PyArg_ParseTuple(args, "iiO|O", &type, &id, &parts, &part_type_list)) return -1;
63    
64            if (!PySequence_Check(parts))
65            {
66                    PyErr_SetString(PyExc_TypeError, "parts is not a sequence");
67                    return -1;
68            }
69            num_parts = PySequence_Length(parts);
70            if (num_parts < 0)
71            {
72                    PyErr_SetString(PyExc_TypeError, "cannot determine length of parts");
73                    return -1;
74            }
75            
76            /* parts and part_types have to have the same lengths */
77            if (part_type_list == Py_None)
78            {
79                    Py_DECREF(part_type_list);
80                    part_type_list = NULL;
81            }
82            if (part_type_list)
83            {
84                    if (!PySequence_Check(parts))
85                    {
86                            PyErr_SetString(PyExc_TypeError, "part_type_list is not a sequence");
87                            return -1;
88                    }
89                    if (PySequence_Length(part_type_list) != num_parts)
90                    {
91                            PyErr_SetString(PyExc_TypeError, "parts and part_types have to have the same lengths");
92                            return -1;
93                    }
94            }
95    
96            /* determine how many vertices there are altogether */
97            num_vertices = 0;
98            for (i = 0; i < num_parts; ++i)
99            {
100                    PyObject* part = PySequence_ITEM(parts, i);
101                    if (!PySequence_Check(part))
102                    {
103                            PyErr_SetString(PyExc_TypeError, "at least one item in parts is not a sequence");
104                            Py_DECREF(part);
105                            return -1;
106                    }
107                    num_vertices += PySequence_Length(part);
108                    Py_DECREF(part);
109            }
110    
111            /* allocate the memory for the various arrays and check for memory errors */
112            xs = malloc(num_vertices * sizeof(double));
113            ys = malloc(num_vertices * sizeof(double));
114            part_starts = malloc(num_parts * sizeof(int));
115            part_types = part_type_list ? malloc(num_parts * sizeof(int)) : 0;
116    
117            if (!xs || !ys || !part_starts || (part_type_list && !part_types))
118            {
119                    PyErr_NoMemory();
120                    goto exit;
121            }
122    
123            /* convert the part types */
124            if (part_type_list)
125            {
126                    for (i = 0; i < num_parts; i++)
127                    {
128                            PyObject* otype = PySequence_ITEM(part_type_list, i);
129                            part_types[i] = PyInt_AsLong(otype);
130                            Py_DECREF(otype);
131                            if (part_types[i] < 0)
132                            {
133                                    PyErr_SetString(PyExc_TypeError, "at least one item in part_type_list is not an integer or is negative");
134                                    goto exit;
135                            }
136                    }
137            }
138    
139            /* convert the list of parts */
140            part_start = 0;
141            for (i = 0; i < num_parts; ++i)
142            {
143                    int j, length;
144                    
145                    PyObject* part = PySequence_ITEM(parts, i);
146                    length = PySequence_Length(part);
147                    part_starts[i] = part_start;
148    
149                    for (j = 0; j < length; ++j)
150                    {
151                            PyObject* vertex = PySequence_ITEM(part, j);
152                            if (!PyArg_ParseTuple(vertex, "dd", xs + part_start + j, ys + part_start + j))
153                            {
154                                    PyErr_SetString(PyExc_TypeError, "at least one part contains an vertex that's not a tuple of two doubles");
155                                    Py_DECREF(vertex);
156                                    Py_DECREF(part);
157                                    goto exit;
158                            }
159                            Py_DECREF(vertex);
160                    }
161                    Py_DECREF(part);
162                    part_start += length;
163            }
164    
165            self->shpObject = SHPCreateObject(type, id, num_parts, part_starts, part_types, num_vertices, xs, ys, NULL, NULL);
166            return_code = 0;
167            
168    exit:
169            free(xs);
170            free(ys);
171            free(part_starts);
172            free(part_types);
173            return return_code;
174    }
175    
 #define delete_SHPObject SHPDestroyObject  
       
176  /*  /*
177   * The extents() method of SHPObject.  * The extents() method of SHPObject.
178   *  *
179   * Return the extents as a tuple of two 4-element lists with the min.  * Return the extents as a tuple of two 4-element lists with the min.
180   * and max. values of x, y, z, m.  * and max. values of x, y, z, m.
181   */  */
182  static PyObject *  static PyObject* shpobject_extents(SHPObjectObject* self)
 SHPObject_extents(SHPObject *object)  
183  {  {
184      return Py_BuildValue("[dddd][dddd]",          SHPObject* object = self->shpObject;
185                           object->dfXMin, object->dfYMin, object->dfZMin,          return Py_BuildValue("(dddd)(dddd)",
186                           object->dfMMin,                          object->dfXMin, object->dfYMin, object->dfZMin, object->dfMMin,
187                           object->dfXMax, object->dfYMax, object->dfZMax,                          object->dfXMax, object->dfYMax, object->dfZMax, object->dfMMax);
                          object->dfMMax);  
188  }  }
189    
190    
191  /*  /*
192   * The vertices() method of SHPObject.  * The vertices() method of SHPObject.
193   *  *
194   * Return the x and y coords of the vertices as a list of lists of  * Return the x and y coords of the vertices as a list of lists of
195   * tuples.  * tuples.
196   */  */
197    
198  static PyObject* build_vertex_list(SHPObject *object, int index, int length);  static PyObject* build_vertex_list(SHPObject *object, int index, int length);
199    
200  static PyObject*  static PyObject* shpobject_vertices(SHPObjectObject* self)
 SHPObject_vertices(SHPObject *object)  
201  {  {
202      PyObject *result = NULL;          PyObject *result = NULL;
203      PyObject *part = NULL;          PyObject *part = NULL;
204      int part_idx, vertex_idx;          int part_idx, vertex_idx;
205      int length = 0;          int length = 0;
206            SHPObject* object = self->shpObject;
207    
208      if (object->nParts > 0)          if (object->nParts > 0)
209      {          {
210          /* A multipart shape. Usual for SHPT_ARC and SHPT_POLYGON */                  /* A multipart shape. Usual for SHPT_ARC and SHPT_POLYGON */
211                    
212          result = PyList_New(object->nParts);                  result = PyList_New(object->nParts);
213          if (!result)                  if (!result)
214              return NULL;                          return NULL;
215    
216                    for (part_idx = 0, vertex_idx = 0; part_idx < object->nParts; part_idx++)
217                    {
218                            if (part_idx < object->nParts - 1)
219                            length = (object->panPartStart[part_idx + 1]
220                                    - object->panPartStart[part_idx]);
221                            else
222                            length = object->nVertices - object->panPartStart[part_idx];
223                            
224                            part = build_vertex_list(object, vertex_idx, length);
225                            if (!part)
226                            goto fail;
227    
228                            if (PyList_SetItem(result, part_idx, part) < 0)
229                            goto fail;
230    
231          for (part_idx = 0, vertex_idx = 0; part_idx < object->nParts;                          vertex_idx += length;
232               part_idx++)                  }
233            }
234            else
235          {          {
236              if (part_idx < object->nParts - 1)                  /* only one part. usual for SHPT_POINT */
237                  length = (object->panPartStart[part_idx + 1]                  result = build_vertex_list(object, 0, object->nVertices);
238                            - object->panPartStart[part_idx]);          }
239              else  
240                  length = object->nVertices - object->panPartStart[part_idx];          return result;
241                
242              part = build_vertex_list(object, vertex_idx, length);  fail:
243              if (!part)          Py_XDECREF(part);
244                  goto fail;          Py_DECREF(result);
245            return NULL;
             if (PyList_SetItem(result, part_idx, part) < 0)  
                 goto fail;  
   
             vertex_idx += length;  
         }  
     }  
     else  
     {  
         /* only one part. usual for SHPT_POINT */  
         result = build_vertex_list(object, 0, object->nVertices);  
     }  
   
     return result;  
   
  fail:  
     Py_XDECREF(part);  
     Py_DECREF(result);  
     return NULL;  
246  }  }
247    
248    
249  /* Return the length coordinates of the shape object starting at vertex  /* Return the length coordinates of the shape object starting at vertex
250   * index as a Python-list of tuples. Helper function for  * index as a Python-list of tuples. Helper function for
251   * SHPObject_vertices.  * SHPObject_vertices.
252   */  */
253  static PyObject*  static PyObject* build_vertex_list(SHPObject *object, int index, int length)
 build_vertex_list(SHPObject *object, int index, int length)  
254  {  {
255      int i;          int i;
256      PyObject * list;          PyObject * list;
257      PyObject * vertex = NULL;          PyObject * vertex = NULL;
258    
259      list = PyList_New(length);          list = PyList_New(length);
260      if (!list)          if (!list)
261          return NULL;                  return NULL;
262    
263      for (i = 0; i < length; i++, index++)          for (i = 0; i < length; i++, index++)
264      {          {
265          vertex = Py_BuildValue("dd", object->padfX[index],                  vertex = Py_BuildValue("dd", object->padfX[index],
266                                 object->padfY[index]);                                          object->padfY[index]);
267          if (!vertex)                  if (!vertex)
268              goto fail;                          goto fail;
269          if (PyList_SetItem(list, i, vertex) < 0)                  if (PyList_SetItem(list, i, vertex) < 0)
270              goto fail;                          goto fail;
271      }          }
   
     return list;  
   
  fail:  
     Py_XDECREF(vertex);  
     Py_DECREF(list);  
     return NULL;  
 }  
272    
273            return list;
274    
275    fail:
276            Py_XDECREF(vertex);
277            Py_DECREF(list);
278            return NULL;
279    }
280    
281    
282    
283  /* The constructor of SHPObject. parts is a list of lists of tuples  static PyObject* shpobject_part_types(SHPObjectObject* self)
  * describing the parts and their vertices just likethe output of the  
  * vertices() method. part_type_list is the list of part-types and may  
  * be NULL. For the meaning of the part-types and their default value  
  * see the Shaplib documentation.  
  */  
 SHPObject * new_SHPObject(int type, int id, PyObject * parts,  
                           PyObject * part_type_list)  
284  {  {
285      /* arrays to hold thex and y coordinates of the  vertices */          int i;
286      double *xs = NULL, *ys = NULL;          PyObject* result = NULL;
287      /* number of all vertices of all parts */          SHPObject* object = self->shpObject;
288      int num_vertices;          
289      /* number of parts in the list parts */          if (object->nParts == 0 || object->panPartType == 0)
     int num_parts;  
     /* start index of in xs and ys of the part currently worked on */  
     int part_start;  
     /* array of start indices in xs and ys as expected by shapelib */  
     int *part_starts = NULL;  
   
     /* generic counter */  
     int i;  
   
     /* array of part types. holds the converted content of  
      * part_type_list. Stays NULL of part_type_list is NULL  
      */  
     int *part_types = NULL;  
   
     /* temporary python objects referring to the the list items being  
      * worked on.  
      */  
     PyObject * part = NULL, *tuple = NULL;  
   
     /* The result object */  
     SHPObject *result;  
   
     num_parts = PySequence_Length(parts);  
     num_vertices = 0;  
   
     /* parts and part_types have to have the same lengths */  
     if (part_type_list  
         && PySequence_Length(parts) != PySequence_Length(part_type_list))  
     {  
         PyErr_SetString(PyExc_TypeError,  
                         "parts and part_types have to have the same lengths");  
         return NULL;  
     }  
   
     /* determine how many vertices there are altogether */  
     for (i = 0; i < num_parts; i++)  
     {  
         PyObject * part = PySequence_GetItem(parts, i);  
         if (!part)  
             return NULL;  
         num_vertices += PySequence_Length(part);  
         Py_DECREF(part);  
     }  
   
     /* allocate the memory for the various arrays and check for memory  
        errors */  
     xs = malloc(num_vertices * sizeof(double));  
     ys = malloc(num_vertices * sizeof(double));  
     part_starts = malloc(num_parts * sizeof(int));  
     if (part_type_list)  
         part_types = malloc(num_parts * sizeof(int));  
   
     if (!xs || !ys || !part_starts || (part_type_list && !part_types))  
     {  
         PyErr_NoMemory();  
         goto fail;  
     }  
   
     /* convert the part types */  
     if (part_type_list)  
     {  
         for (i = 0; i < num_parts; i++)  
290          {          {
291              PyObject * otype = PySequence_GetItem(part_type_list, i);                  Py_RETURN_NONE;
             if (!otype)  
                 return NULL;  
             part_types[i] = PyInt_AsLong(otype);  
             Py_DECREF(otype);  
292          }          }
293      }          
294            result = PyTuple_New(object->nParts);
295      /* convert the list of parts */          if (!result) return NULL;
296      part_start = 0;          
297      for (i = 0; i < num_parts; i++)          for (i = 0; i < object->nParts; ++i)
298      {          {
299          int j, length;                  /* PyTuple_SetItem steals a reference */
300                    PyObject* part_type = PyInt_FromLong((long)object->panPartType[i]);
301          part = PySequence_GetItem(parts, i);                  if (!part_type || PyTuple_SetItem(result, i, part_type) < 0) goto fail;
302          length = PySequence_Length(part);          }      
303          part_starts[i] = part_start;          return result;
304            
305          for (j = 0; j < length; j++)  fail:
306          {          Py_DECREF(result);
307              tuple = PySequence_GetItem(part, j);          return NULL;
             if (!tuple)  
                 goto fail;  
   
             if (!PyArg_ParseTuple(tuple, "dd", xs + part_start + j,  
                                   ys + part_start + j))  
             {  
                 goto fail;  
             }  
             Py_DECREF(tuple);  
             tuple = NULL;  
         }  
         Py_DECREF(part);  
         part = NULL;  
         part_start += length;  
     }  
   
     result = SHPCreateObject(type, id, num_parts, part_starts, part_types,  
                              num_vertices, xs, ys, NULL, NULL);  
     free(xs);  
     free(ys);  
     free(part_starts);  
     free(part_types);  
     return result;  
   
  fail:  
     free(xs);  
     free(ys);  
     free(part_starts);  
     free(part_types);  
     Py_XDECREF(part);  
     Py_XDECREF(tuple);  
     return NULL;  
308  }  }
309    
 %}  
310    
311    
312    static PyObject* shpobject_type(SHPObjectObject* self, void* closure)
313    {
314            return PyInt_FromLong(self->shpObject->nSHPType);
315    }
316    
 /*  
  * The SWIG Interface definition.  
  */  
317    
 /* include some common SWIG type definitions and standard exception  
    handling code */  
 %include typemaps.i  
 %include exception.i  
318    
319    static PyObject* shpobject_id(SHPObjectObject* self, void* closure)
320    {
321            return PyInt_FromLong(self->shpObject->nShapeId);
322    }
323    
324  /*  
325   *  SHPObject -- Represents one shape  
326    /* return a string that can be feeded to eval() to reconstruct the object,
327     * assuming a proper context
328   */   */
329    static PyObject* shpobject_repr(SHPObjectObject* self)
330    {
331            PyObject* format = NULL;
332            PyObject* args = NULL;
333            PyObject* result = NULL;
334            
335            format = PyString_FromString("shapelib.SHPObject(%i, %i, %s, %s)");
336            if (!format) return NULL;
337    
338  /* Exception typemap for the SHPObject constructor. The constructor the          args = Py_BuildValue("iiNN",
339     the wrapper function defined above which returns NULL in case of                  self->shpObject->nSHPType,
340     error. */                  self->shpObject->nShapeId,
341                      shpobject_vertices(self),
342  %typemap(python,except) SHPObject*new_SHPObject {                  shpobject_part_types(self));
343      $function;          if (!args)
344      if (PyErr_Occurred())          {
345          return NULL;                  Py_DECREF(format);
346                    return NULL;
347            }
348            
349            result = PyString_Format(format, args);
350            Py_DECREF(args);
351            Py_DECREF(format);
352            return result;
353  }  }
354    
 /* Define the SHPObject struct for SWIG. This has to have the same name  
  * as the underlying C-struct in shapfil.h, but we don't have to repeat  
  * all the fields here, only those we want to access directly, and we  
  * can define methods for the object oriented interface.  
  */  
355    
 typedef struct {  
356    
357      /* The shape object has two read-only attributes: */  static struct PyMethodDef shpobject_methods[] =
358    {
359            {"extents", (PyCFunction)shpobject_extents, METH_NOARGS, NULL},
360            {"vertices", (PyCFunction)shpobject_vertices, METH_NOARGS, NULL},
361            {"part_types", (PyCFunction)shpobject_part_types, METH_NOARGS, NULL},
362            {NULL}
363    };
364    
365      /* The type of the shape. In the c-struct defined the field is  static struct PyGetSetDef shpobject_getsetters[] =
366       * called 'nSHPType' but for the python bindings 'type' is more  {
367       * appropriate.          {"type", (getter)shpobject_type, NULL, NULL },
368       */          {"id", (getter)shpobject_id, NULL, NULL },
369      %readonly %name(type) int nSHPType;          {NULL}
370    };
     /* The id of the shape. Here 'id' is a better name than 'nShapeId'. */  
     %readonly %name(id) int nShapeId;  
   
     /* The methods */  
     %addmethods {  
   
         /* the constructor */  
         SHPObject(int type, int id, PyObject * parts,  
                   PyObject * part_types = NULL);  
   
         /* The destructor */  
         ~SHPObject();  
   
         /* extents and vertices correspond to the SHPObject_extents and  
          * SHPObject_vertices defined above  
          */  
         PyObject *extents();  
         PyObject *vertices();  
     }  
 } SHPObject;  
371    
372    static PyTypeObject SHPObjectType = PYSHAPELIB_DEFINE_TYPE(SHPObjectObject, shpobject, "shapelib.SHPObject", 0);
373    
 /*  
  * ShapeFile --  Represents the shape file  
  */  
374    
375  /* Here we do things a little different. We define a new C-struct that  /* --- ShapeFile ----------------------------------------------------------------------------------------------------- */
  * holds the SHPHandle. This is mainly done so we can separate the  
  * close() method from the destructor but it also helps with exception  
  * handling.  
  *  
  * After the ShapeFile has been opened or created the handle is not  
  * NULL. The close() method closes the file and sets handle to NULL as  
  * an indicator that the file has been closed.  
  */  
376    
377  /* First, define the C-struct */  typedef struct
378  %{  {
379      typedef struct {          PyObject_HEAD
380          SHPHandle handle;          SHPHandle handle;
381      } ShapeFile;  }
382  %}  ShapeFileObject;
383    
384  /* define and use some typemaps for the info() method whose  /* allocator
  * C-implementation has four output parameters that are returned through  
  * pointers passed into the function. SWIG already has definitions for  
  * common types such as int* and we can use those for the first two  
  * parameters:  
385   */   */
386    static PyObject* shapefile_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
387  %apply int * OUTPUT { int * output_entities }  {
388  %apply int * OUTPUT { int * output_type }          ShapeFileObject* self;  
389            self = (ShapeFileObject*) type->tp_alloc(type, 0);
390            self->handle = NULL;
391            return (PyObject*) self;
392    }
393    
394  /* for the last two, the 4-element arrays of min- and max-values, we  /* destructor
395   * have to define our own typemaps:  */
396   */  static void shapefile_dealloc(ShapeFileObject* self)
397  %typemap (python,ignore) double * extents(double temp[4]) {  {
398      $target = temp;          SHPClose(self->handle);
399            self->ob_type->tp_free((PyObject*)self);
400  }  }
401    
402  %typemap (python,argout) double * extents {  /* constructor
     PyObject * list = Py_BuildValue("[dddd]",  
                                     $source[0], $source[1],  
                                     $source[2], $source[3]);  
     $target = t_output_helper($target,list);  
 }  
   
 %apply double * extents { double * output_min_bounds }  
 %apply double * extents { double * output_max_bounds }  
   
 /* The first argument to the ShapeFile methods is a ShapeFile pointer.  
  * We have to check whether handle is not NULL in most methods but not  
  * all. In the destructor and the close method, it's OK for handle to be  
  * NULL. We achieve this by checking whether the preprocessor macro  
  * NOCHECK_$name is defined. SWIG replaces $name with the name of the  
  * function for which the code is inserted. In the %{,%}-block below we  
  * define the macros for the destructor and the close() method.  
403   */   */
404    static int shapefile_init(ShapeFileObject* self, PyObject* args, PyObject* kwds)
405    {
406            char* file;
407            char* mode = "rb";
408            if (kwds != NULL && PyDict_Size(kwds) > 0)
409            {
410                    PyErr_Format(PyExc_TypeError, "shapelib.ShapeFile.__init__ takes no keyword arguments");
411                    return -1;
412            }
413            if (!PyArg_ParseTuple(args, "s|s", &file, &mode)) return -1;
414            
415            self->handle = SHPOpen(file, mode);
416            return self->handle ? 0 : -1;
417    }
418    
419    static PyObject* shapefile_close(ShapeFileObject* self)
420    {
421            SHPClose(self->handle);
422            self->handle = NULL;
423            Py_RETURN_NONE;
424    }
425    
426  %typemap(python,check) ShapeFile *{  static PyObject* shapefile_info(ShapeFileObject* self)
427      %#ifndef NOCHECK_$name  {
428      if (!$target || !$target->handle)          SHPHandle handle = self->handle;
429          SWIG_exception(SWIG_TypeError, "shapefile already closed");          return Py_BuildValue("ii(dddd)(dddd)",
430      %#endif                          handle->nRecords, handle->nShapeType,
431  }                          handle->adBoundsMin[0], handle->adBoundsMin[1], handle->adBoundsMin[2], handle->adBoundsMin[3],
432                            handle->adBoundsMax[0], handle->adBoundsMax[1], handle->adBoundsMax[2], handle->adBoundsMax[3]);
 %{  
 #define NOCHECK_delete_ShapeFile  
 #define NOCHECK_ShapeFile_close  
 %}  
   
 /* An exception handle for the constructor and the module level open()  
  * and create() functions.  
  *  
  * Annoyingly, we *have* to put braces around the SWIG_exception()  
  * calls, at least in the python case, because of the way the macro is  
  * written. Of course, always putting braces around the branches of an  
  * if-statement is often considered good practice.  
  */  
 %typemap(python,except) ShapeFile * {  
     $function;  
     if (!$source)  
     {  
         SWIG_exception(SWIG_MemoryError, "no memory");  
     }  
     else if (!$source->handle)  
     {  
         SWIG_exception(SWIG_IOError, "$name failed");  
     }  
433  }  }
434    
435    static PyObject* shapefile_read_object(ShapeFileObject* self, PyObject* args)
436    {
437            int index;
438            SHPObject* object;
439            SHPObjectObject* result;
440            
441            if (!PyArg_ParseTuple(args, "i", &index)) return NULL;
442            
443            object = SHPReadObject(self->handle, index);    
444            if (!object)
445            {
446                    PyErr_SetString(PyExc_RuntimeError, "failed to read object");
447                    return NULL;
448            }
449            
450            result = PyObject_New(SHPObjectObject, &SHPObjectType);
451            if (!result)
452            {
453                    return PyErr_NoMemory();
454            }
455            
456            result->shpObject = object;
457            return (PyObject*) result;
458    }
459    
460  /*  static PyObject* shapefile_write_object(ShapeFileObject* self, PyObject* args)
461   * The SWIG-version of the ShapeFile struct.  {
462   */          int index, result;
463            PyObject* object;
464            
465            if (!PyArg_ParseTuple(args, "iO", &index, &object)) return NULL;
466            
467            if (!PyObject_IsInstance(object, (PyObject*)&SHPObjectType))
468            {
469                    PyErr_SetString(PyExc_TypeError, "object is not a SHPObject");
470                    return NULL;
471            }
472            
473            result = SHPWriteObject(self->handle, index, ((SHPObjectObject*)object)->shpObject);
474            if (result < 0)
475            {
476                    PyErr_SetString(PyExc_RuntimeError, "failed to write object");
477                    return NULL;
478            }
479            return PyInt_FromLong((long)result);
480    }
481    
482  typedef struct  static PyObject* shapefile_cobject(ShapeFileObject* self)
483  {  {
484      /* Only methods and no attributes here: */          return PyCObject_FromVoidPtr(self->handle, NULL);
485      %addmethods {  }
486    
487          /* The constructor. Takes two arguments, the filename and the  static PyObject* shapefile_repr(ShapeFileObject* self)
488           * optinal mode which are passed through to SHPOpen (due to the  {
489           * renaming trick)          /* TODO: it would be nice to do something like "shapelib.ShapeFile(filename, mode)" instead */
490           */          return PyString_FromFormat("<shapelib.ShapeFile object at %p>", self->handle);
491          ShapeFile(char *file, char * mode = "rb") {  }
             ShapeFile * self = malloc(sizeof(ShapeFile));  
             if (self)  
                 self->handle = SHPOpen(file, mode);  
             return self;  
         }  
   
         /* The destructor. Equivalent to SHPClose */  
         ~ShapeFile() {  
             if (self->handle)  
                 SHPClose(self->handle);  
             free(self);  
         }  
   
         /* close the shape file and set handle to NULL */  
         void close() {  
             if (self->handle)  
             {  
                 SHPClose(self->handle);  
                 self->handle = NULL;  
             }  
         }  
   
         /* info() -- Return a tuple (NUM_SHAPES, TYPE, MIN, MAX) where  
          * NUM_SHAPES is the number of shapes in the file, TYPE is the  
          * shape type and MIN and MAX are 4-element lists with the min.  
          * and max. values of the data.  
          *  
          * The arguments of the underlying shapelib function SHPGetInfo  
          * are all output parameters. To tell SWIG this, we have defined  
          * some typemaps above  
          */  
         void info(int * output_entities, int * output_type,  
                   double * output_min_bounds, double *output_max_bounds) {  
             SHPGetInfo(self->handle, output_entities, output_type,  
                        output_min_bounds, output_max_bounds);  
         }  
   
         /* Return object number i */  
         %new SHPObject * read_object(int i) {  
             return SHPReadObject(self->handle, i);  
         }  
   
         /* Write an object */  
         int write_object(int iShape, SHPObject * psObject) {  
             return SHPWriteObject(self->handle, iShape, psObject);  
         }  
   
         /* Return the shapelib SHPHandle as a Python CObject */  
         PyObject * cobject() {  
             return PyCObject_FromVoidPtr(self->handle, NULL);  
         }  
     }  
492    
493  } ShapeFile;  static struct PyMethodDef shapefile_methods[] =
494    {
495            {"close", (PyCFunction)shapefile_close, METH_NOARGS, "close the shape file" },
496            {"info", (PyCFunction)shapefile_info, METH_NOARGS,
497                    "Return a tuple (NUM_SHAPES, TYPE, MIN, MAX) where NUM_SHAPES is the number of shapes in the file, TYPE is the "
498                    "shape type and MIN and MAX are 4-element tuples with the min. and max. values of the data." },
499            {"read_object", (PyCFunction)shapefile_read_object, METH_VARARGS, "Return object number i" },
500            {"write_object", (PyCFunction)shapefile_write_object, METH_VARARGS, "Write an object"},
501            {"cobject", (PyCFunction)shapefile_cobject, METH_NOARGS, "Return the shapelib SHPHandle as a Python CObject"},
502            {NULL}
503    };
504    
505    static struct PyGetSetDef shapefile_getsetters[] =
506    {
507            {NULL}
508    };
509    
510  /*  static PyTypeObject ShapeFileType = PYSHAPELIB_DEFINE_TYPE(ShapeFileObject, shapefile, "shapelib.ShapeFile", 0);
  * Two module level functions, open() and create() that correspond to  
  * SHPOpen and SHPCreate respectively. open() is equivalent to the  
  * ShapeFile constructor.  
  */  
511    
512  %{  /* --- shapelib ------------------------------------------------------------------------------------------------------ */
     ShapeFile * open_ShapeFile(const char *filename, const char * mode) {  
         ShapeFile * self = malloc(sizeof(ShapeFile));  
         if (self)  
             self->handle = SHPOpen(filename, mode);  
         return self;  
     }  
 %}  
   
 %name(open) %new ShapeFile *open_ShapeFile(const char *filename,  
                                            const char * mode = "rb");  
   
   
 %{  
     ShapeFile * create_ShapeFile(const char *filename, int type) {  
         ShapeFile * self = malloc(sizeof(ShapeFile));  
         if (self)  
             self->handle = SHPCreate(filename, type);  
         return self;  
     }  
 %}      
   
 %name(create) %new ShapeFile * create_ShapeFile(const char *filename,  
                                                 int type);  
       
   
 /* Module level function to expose some of the shapelib functions linked  
  * with the shapefile C-module to other Python extension modules. This  
  * is a kludge to make a Thuban extension work that reads shapes from  
  * shapefiles opened by the shapefile module.  
  */  
513    
514  %{  static PyObject* shapelib_open(PyObject* module, PyObject* args)
515      static PyShapeLibAPI the_api = {  {
516            return PyObject_CallObject((PyObject*)&ShapeFileType, args);
517    }
518    
519    static PyObject* shapelib_create(PyObject* module, PyObject* args)
520    {
521            char* file;
522            int type;
523            ShapeFileObject* result;
524            
525            if (!PyArg_ParseTuple(args, "si", &file, &type)) return NULL;
526            
527            result = PyObject_New(ShapeFileObject, &ShapeFileType);
528            if (!result)
529            {
530                    return PyErr_NoMemory();
531            }
532            
533            result->handle = SHPCreate(file, type);
534            if (!result->handle)
535            {
536                    PyObject_Del((PyObject*)result);
537                    PyErr_SetString(PyExc_RuntimeError, "Failed to create ShapeFile");
538                    return NULL;
539            }
540            
541            return (PyObject*) result;
542    }
543            
544    static PyShapeLibAPI shapelib_the_api =
545    {
546          SHPReadObject,          SHPReadObject,
547          SHPDestroyObject,          SHPDestroyObject,
548          SHPCreateTree,          SHPCreateTree,
549          SHPDestroyTree,          SHPDestroyTree,
550          SHPTreeFindLikelyShapes          SHPTreeFindLikelyShapes
551      };  };
   
     PyObject * c_api() {  
         return PyCObject_FromVoidPtr(&the_api, NULL);  
     }  
 %}  
   
 PyObject * c_api();  
552    
553    static PyObject* shapelib_c_api(PyObject* module)
554    {
555            return PyCObject_FromVoidPtr(&shapelib_the_api, NULL);
556    }
557    
558  /*  static PyObject* shapelib_type_name(PyObject* module, PyObject* args)
559   *  Module Level functions  {
560   */          int type;
561            if (!PyArg_ParseTuple(args, "i", &type)) return NULL;
562  /* convert shapefile types to names */          return PyString_FromString(SHPTypeName(type));
563  %name(type_name) const char *SHPTypeName(int nSHPType);  }
 %name(part_type_name) const char *SHPPartTypeName(int nPartType);  
   
564    
565  /*  static PyObject* shapelib_part_type_name(PyObject* module, PyObject* args)
566   * Finally, constants copied from shapefil.h  {
567   */          int type;
568            if (!PyArg_ParseTuple(args, "i", &type)) return NULL;
569            return PyString_FromString(SHPPartTypeName(type));
570    }
571    
572  /* -------------------------------------------------------------------- */  static struct PyMethodDef shapelib_methods[] =
573  /*      Shape types (nSHPType)                                          */  {
574  /* -------------------------------------------------------------------- */          {"open", (PyCFunction)shapelib_open, METH_VARARGS, "open a ShapeFile" },
575  #define SHPT_NULL       0          {"create", (PyCFunction)shapelib_create, METH_VARARGS, "create a ShapeFile" },
576  #define SHPT_POINT      1          {"c_api", (PyCFunction)shapelib_c_api, METH_NOARGS, "get C API of shapelib" },
577  #define SHPT_ARC        3          {"type_name", (PyCFunction)shapelib_type_name, METH_VARARGS, "return type as string" },
578  #define SHPT_POLYGON    5          {"part_type_name", (PyCFunction)shapelib_part_type_name, METH_VARARGS, "return part type as string" },
579  #define SHPT_MULTIPOINT 8          {NULL}
580  #define SHPT_POINTZ     11  };
 #define SHPT_ARCZ       13  
 #define SHPT_POLYGONZ   15  
 #define SHPT_MULTIPOINTZ 18  
 #define SHPT_POINTM     21  
 #define SHPT_ARCM       23  
 #define SHPT_POLYGONM   25  
 #define SHPT_MULTIPOINTM 28  
 #define SHPT_MULTIPATCH 31  
   
   
 /* -------------------------------------------------------------------- */  
 /*      Part types - everything but SHPT_MULTIPATCH just uses           */  
 /*      SHPP_RING.                                                      */  
 /* -------------------------------------------------------------------- */  
   
 #define SHPP_TRISTRIP   0  
 #define SHPP_TRIFAN     1  
 #define SHPP_OUTERRING  2  
 #define SHPP_INNERRING  3  
 #define SHPP_FIRSTRING  4  
 #define SHPP_RING       5  
581    
582    PyMODINIT_FUNC initshapelib(void)
583    {
584            PyObject* module = Py_InitModule("shapelib", shapelib_methods);
585            if (!module) return;
586            
587            PYSHAPELIB_ADD_TYPE(SHPObjectType, "SHPObject");
588            PYSHAPELIB_ADD_TYPE(ShapeFileType, "ShapeFile");
589            
590            PYSHAPELIB_ADD_CONSTANT(SHPT_NULL);
591            PYSHAPELIB_ADD_CONSTANT(SHPT_POINT);
592            PYSHAPELIB_ADD_CONSTANT(SHPT_ARC);
593            PYSHAPELIB_ADD_CONSTANT(SHPT_POLYGON);
594            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPOINT);
595            PYSHAPELIB_ADD_CONSTANT(SHPT_POINTZ);
596            PYSHAPELIB_ADD_CONSTANT(SHPT_ARCZ);
597            PYSHAPELIB_ADD_CONSTANT(SHPT_POLYGONZ);
598            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPOINTZ);
599            PYSHAPELIB_ADD_CONSTANT(SHPT_POINTM);
600            PYSHAPELIB_ADD_CONSTANT(SHPT_ARCM);
601            PYSHAPELIB_ADD_CONSTANT(SHPT_POLYGONM);
602            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPOINTM);
603            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPATCH);
604            PYSHAPELIB_ADD_CONSTANT(SHPP_TRISTRIP);
605            PYSHAPELIB_ADD_CONSTANT(SHPP_TRIFAN);
606            PYSHAPELIB_ADD_CONSTANT(SHPP_OUTERRING);
607            PYSHAPELIB_ADD_CONSTANT(SHPP_INNERRING);
608            PYSHAPELIB_ADD_CONSTANT(SHPP_FIRSTRING);
609            PYSHAPELIB_ADD_CONSTANT(SHPP_RING);
610    }
611    

Legend:
Removed from v.2637  
changed lines
  Added in v.2742

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26