/[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 1611 by jan, Tue Aug 19 21:24:20 2003 UTC branches/WIP-pyshapelib-bramz/libraries/pyshapelib/shapelibmodule.c revision 2745 by bramz, Thu Mar 15 22:27:02 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  %{  enum {
13            vtXY,
14            vtXYM,
15            vtXYZM,
16            vtInvalid
17    } VertexType;
18    
19  /* import the shapelib headefile. */  int determine_vertex_type(int shape_type, int* has_z, int* has_m)
20  #include "shapefil.h"  {
21  #include "pyshapelib_api.h"          switch (shape_type)
22                {
23  /*          case SHPT_POINT:
24   * Rename a few shapelib functions that are effectively methods with          case SHPT_ARC:
25   * preprocessor macros so that they have the names that swig expects          case SHPT_POLYGON:
26   * (e.g. the destructor of SHPObject has to be called delete_SHPObject)          case SHPT_MULTIPOINT:
27   */                  if (has_z) *has_z = 0;
28                    if (has_m) *has_m = 0;
29  #define delete_SHPObject SHPDestroyObject                  return vtXY;
30                case SHPT_POINTM:
31  /*          case SHPT_ARCM:
32   * The extents() method of SHPObject.          case SHPT_POLYGONM:
33   *          case SHPT_MULTIPOINTM:
34   * Return the extents as a tuple of two 4-element lists with the min.                  if (has_z) *has_z = 0;
35   * and max. values of x, y, z, m.                  if (has_m) *has_m = 1;
36            case SHPT_POINTZ:
37            case SHPT_ARCZ:
38            case SHPT_POLYGONZ:
39            case SHPT_MULTIPOINTZ:
40            case SHPT_MULTIPATCH:
41                    if (has_z) *has_z = 1;
42                    if (has_m) *has_m = 1;
43                    return vtXYZM;
44            default:
45                    if (has_z) *has_z = 0;
46                    if (has_m) *has_m = 0;
47                    return vtInvalid;
48            }
49    }
50            
51    /* allocator
52   */   */
53  static PyObject *  static PyObject* shpobject_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
 SHPObject_extents(SHPObject *object)  
54  {  {
55      return Py_BuildValue("[dddd][dddd]",          SHPObjectObject* self;  
56                           object->dfXMin, object->dfYMin, object->dfZMin,          self = (SHPObjectObject*) type->tp_alloc(type, 0);
57                           object->dfMMin,          self->shpObject = NULL;
58                           object->dfXMax, object->dfYMax, object->dfZMax,          return (PyObject*) self;
                          object->dfMMax);  
59  }  }
60    
61    /* deallocator
 /*  
  * The vertices() method of SHPObject.  
  *  
  * Return the x and y coords of the vertices as a list of lists of  
  * tuples.  
62   */   */
63    static void shpobject_dealloc(SHPObjectObject* self)
64    {
65            SHPDestroyObject(self->shpObject);
66            self->shpObject = NULL;
67            self->ob_type->tp_free((PyObject*)self);
68    }
69    
70  static PyObject* build_vertex_list(SHPObject *object, int index, int length);  static int unpack_vertex(PyObject* vertex, int vertex_type,
71                    double* xs, double* ys, double* zs, double* ms, int offset);
72    
73  static PyObject*  /* The constructor of SHPObject. parts is a list of lists of tuples
74  SHPObject_vertices(SHPObject *object)  * describing the parts and their vertices just likethe output of the
75    * vertices() method. part_type_list is the list of part-types and may
76    * be NULL. For the meaning of the part-types and their default value
77    * see the Shaplib documentation.
78    */
79    static int shpobject_init(SHPObjectObject* self, PyObject* args, PyObject* kwds)
80  {  {
81      PyObject *result = NULL;          int type;
82      PyObject *part = NULL;          int id;
83      int part_idx, vertex_idx;          PyObject* parts = NULL;
84      int length = 0;          PyObject* part_type_list = NULL;
85            
86            int num_parts;
87            int num_vertices;
88            int part_start;
89            
90            double* xs = NULL;
91            double* ys = NULL;
92            double* zs = NULL;
93            double* ms = NULL;
94            int* part_starts = NULL;
95            int* part_types = NULL;
96            
97            PyObject* part;
98            int vertex_type;
99            int has_z;
100            int has_m;
101            
102            int i;
103            int return_code = -1;
104            
105            /* first, unpack parameters */
106            if (kwds != NULL && PyDict_Size(kwds) > 0)
107            {
108                    PyErr_Format(PyExc_TypeError, "shapelib.SHPObject.__init__ takes no keyword arguments");
109                    return -1;
110            }
111            if (!PyArg_ParseTuple(args, "iiO|O:__init__", &type, &id, &parts, &part_type_list)) return -1;
112    
113            /* check parts */
114            if (!PySequence_Check(parts))
115            {
116                    PyErr_SetString(PyExc_TypeError, "parts is not a sequence");
117                    return -1;
118            }
119            num_parts = PySequence_Length(parts);
120            if (num_parts < 0)
121            {
122                    PyErr_SetString(PyExc_TypeError, "cannot determine length of parts");
123                    return -1;
124            }
125            
126            /* parts and part_types have to have the same lengths */
127            if (part_type_list == Py_None)
128            {
129                    Py_DECREF(part_type_list);
130                    part_type_list = NULL;
131            }
132            if (part_type_list)
133            {
134                    if (!PySequence_Check(parts))
135                    {
136                            PyErr_SetString(PyExc_TypeError, "part_type_list is not a sequence");
137                            return -1;
138                    }
139                    if (PySequence_Length(part_type_list) != num_parts)
140                    {
141                            PyErr_SetString(PyExc_TypeError, "parts and part_types have to have the same lengths");
142                            return -1;
143                    }
144            }
145    
146      if (object->nParts > 0)          /* determine how many vertices there are altogether */
147      {          num_vertices = 0;
148          /* A multipart shape. Usual for SHPT_ARC and SHPT_POLYGON */          for (i = 0; i < num_parts; ++i)
149            {
150                    PyObject* part = PySequence_ITEM(parts, i);
151                    if (!PySequence_Check(part))
152                    {
153                            PyErr_SetString(PyExc_TypeError, "at least one item in parts is not a sequence");
154                            Py_DECREF(part);
155                            return -1;
156                    }
157                    num_vertices += PySequence_Length(part);
158                    Py_DECREF(part);
159            }
160                    
161          result = PyList_New(object->nParts);          
162          if (!result)          vertex_type = determine_vertex_type(type, &has_z, &has_m);
163              return NULL;  
164            /* allocate the memory for the various arrays and check for memory errors */
165            xs = malloc(num_vertices * sizeof(double));
166            ys = malloc(num_vertices * sizeof(double));
167            zs = has_z ? malloc(num_vertices * sizeof(double)) : NULL;
168            ms = has_m ? malloc(num_vertices * sizeof(double)) : NULL;
169            part_starts = malloc(num_parts * sizeof(int));
170            part_types = part_type_list ? malloc(num_parts * sizeof(int)) : 0;
171    
172          for (part_idx = 0, vertex_idx = 0; part_idx < object->nParts;          if (!xs || !ys || (has_z && !zs) || (has_m && !ms) || !part_starts || (part_type_list && !part_types))
              part_idx++)  
173          {          {
174              if (part_idx < object->nParts - 1)                  PyErr_NoMemory();
175                  length = (object->panPartStart[part_idx + 1]                  goto exit;
176                            - object->panPartStart[part_idx]);          }
             else  
                 length = object->nVertices - object->panPartStart[part_idx];  
               
             part = build_vertex_list(object, vertex_idx, length);  
             if (!part)  
                 goto fail;  
   
             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;  
 }  
177    
178            /* convert the part types */
179            if (part_type_list)
180            {
181                    for (i = 0; i < num_parts; i++)
182                    {
183                            PyObject* otype = PySequence_ITEM(part_type_list, i);
184                            part_types[i] = PyInt_AsLong(otype);
185                            Py_DECREF(otype);
186                            if (part_types[i] < 0)
187                            {
188                                    PyErr_SetString(PyExc_TypeError, "at least one item in part_type_list is not an integer or is negative");
189                                    goto exit;
190                            }
191                    }
192            }
193    
194  /* Return the length coordinates of the shape object starting at vertex          /* convert the list of parts */
195   * index as a Python-list of tuples. Helper function for          part_start = 0;
196   * SHPObject_vertices.          for (i = 0; i < num_parts; ++i)
197            {
198                    int j, length;
199                    
200                    part = PySequence_ITEM(parts, i);
201                    length = PySequence_Length(part);
202                    if (length < 0) goto exit;
203                    part_starts[i] = part_start;
204    
205                    for (j = 0; j < length; ++j)
206                    {
207                            PyObject* vertex = PySequence_ITEM(part, j);
208                            if (!unpack_vertex(vertex, vertex_type, xs, ys, zs, ms, part_start + j))
209                            {
210                                    Py_DECREF(vertex);
211                                    PyErr_SetString(PyExc_TypeError, "at least one vertex is of the wrong format");
212                                    goto exit;
213                            }
214                            Py_DECREF(vertex);
215                    }
216                    Py_DECREF(part);
217                    part = NULL;
218                    part_start += length;
219            }
220    
221            self->shpObject = SHPCreateObject(type, id, num_parts, part_starts, part_types, num_vertices, xs, ys, zs, ms);
222            return_code = 0;
223            
224    exit:
225            Py_XDECREF(part);
226            free(xs);
227            free(ys);
228            free(zs);
229            free(ms);
230            free(part_starts);
231            free(part_types);
232            return return_code;
233    }
234    
235    /* helper for shpobject_init. Unpacks vertices
236   */   */
237  static PyObject*  static int unpack_vertex(PyObject* vertex, int vertex_type,
238  build_vertex_list(SHPObject *object, int index, int length)                  double* xs, double* ys, double* zs, double* ms, int offset)
239  {  {
240      int i;          int ok;
241      PyObject * list;          PyObject* m_object;
242      PyObject * vertex = NULL;          PyObject *err_type, *err_value, *err_traceback;
243    
244      list = PyList_New(length);          switch (vertex_type)
245      if (!list)          {
246          return NULL;          case vtXY:
247                    return PyArg_ParseTuple(vertex, "dd:__init__", xs + offset, ys + offset);
248    
249      for (i = 0; i < length; i++, index++)          case vtXYM:
250      {                  ms[offset] = PYSHAPELIB_NO_DATA;
251          vertex = Py_BuildValue("dd", object->padfX[index],                  ok = PyArg_ParseTuple(vertex, "dd|d:__init__", xs + offset, ys + offset, ms + offset);
252                                 object->padfY[index]);                  if (!ok)
253          if (!vertex)                  {
254              goto fail;                          /* maybe they specified None as M value */
255          if (PyList_SetItem(list, i, vertex) < 0)                          PyErr_Fetch(&err_type, &err_value, &err_traceback);
256              goto fail;                          ok = PyArg_ParseTuple(vertex, "ddO:__init__", xs + offset, ys + offset, &m_object);
257      }                          if (ok && m_object == Py_None)
258                            {
259      return list;                                  Py_XDECREF(err_type);
260                                    Py_XDECREF(err_value);
261   fail:                                  Py_XDECREF(err_traceback);
262      Py_XDECREF(vertex);                          }
263      Py_DECREF(list);                          else
264      return NULL;                          {
265                                    PyErr_Restore(err_type, err_value, err_traceback);
266                            }
267                    }
268                    return ok;
269    
270            case vtXYZM:
271                    zs[offset] = 0.;
272                    ms[offset] = PYSHAPELIB_NO_DATA;
273                    ok = PyArg_ParseTuple(vertex, "dd|dd:__init__", xs + offset, ys + offset,
274                                    zs + offset, ms + offset);
275                    if (!ok)
276                    {
277                            /* maybe they specified None as M value */
278                            PyErr_Fetch(&err_type, &err_value, &err_traceback);
279                            ok = PyArg_ParseTuple(vertex, "dddO:__init__", xs + offset, ys + offset,
280                                            zs + offset, &m_object);
281                            if (ok && m_object == Py_None)
282                            {
283                                    Py_XDECREF(err_type);
284                                    Py_XDECREF(err_value);
285                                    Py_XDECREF(err_traceback);
286                            }
287                            else
288                            {
289                                    PyErr_Restore(err_type, err_value, err_traceback);
290                            }
291                    }
292                    return ok;
293    
294            default:
295                    PyErr_SetString(PyExc_NotImplementedError, "vertex type not implemented");
296                    return 0;
297            }
298  }  }
299    
300    /*
301    * The extents() method of SHPObject.
302    *
303    * Return the extents as a tuple of two 4-element lists with the min.
304    * and max. values of x, y, z, m.
305    */
306    static PyObject* shpobject_extents(SHPObjectObject* self)
307    {
308            SHPObject* object = self->shpObject;
309            return Py_BuildValue("(dddd)(dddd)",
310                            object->dfXMin, object->dfYMin, object->dfZMin, object->dfMMin,
311                            object->dfXMax, object->dfYMax, object->dfZMax, object->dfMMax);
312    }
313    
314    
315    /*
316    * The vertices() method of SHPObject.
317    *
318    * Return the x and y coords of the vertices as a list of lists of
319    * tuples.
320    */
321    
322    static PyObject* build_vertex_list(SHPObject *object, int index, int length, int vertex_type);
323    
324  /* The constructor of SHPObject. parts is a list of lists of tuples  static PyObject* shpobject_vertices(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)  
325  {  {
326      /* arrays to hold thex and y coordinates of the  vertices */          PyObject *result = NULL;
327      double *xs = NULL, *ys = NULL;          PyObject *part = NULL;
328      /* number of all vertices of all parts */          int part_idx, vertex_idx;
329      int num_vertices;          int length = 0;
330      /* number of parts in the list parts */          int vertex_type;
331      int num_parts;          
332      /* start index of in xs and ys of the part currently worked on */          SHPObject* object = self->shpObject;
333      int part_start;          vertex_type = determine_vertex_type(object->nSHPType, NULL, NULL);
     /* 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(part) != PySequence_Length(part_type_list))  
     {  
         PyErr_SetString(PyExc_TypeError,  
                         "parts and part_types have to have the same lengths");  
         return NULL;  
     }  
334    
335      /* determine how many vertices there are altogether */          if (object->nParts > 0)
     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++)  
336          {          {
337              PyObject * otype = PySequence_GetItem(part_type_list, i);                  /* A multipart shape. Usual for SHPT_ARC and SHPT_POLYGON */
338              if (!otype)          
339                  return NULL;                  result = PyList_New(object->nParts);
340              part_types[i] = PyInt_AsLong(otype);                  if (!result)
341              Py_DECREF(otype);                          return NULL;
342    
343                    for (part_idx = 0, vertex_idx = 0; part_idx < object->nParts; part_idx++)
344                    {
345                            if (part_idx < object->nParts - 1)
346                                    length = (object->panPartStart[part_idx + 1]
347                                            - object->panPartStart[part_idx]);
348                            else
349                                    length = object->nVertices - object->panPartStart[part_idx];
350                            
351                            part = build_vertex_list(object, vertex_idx, length, vertex_type);
352                            if (!part) goto fail;
353    
354                            if (PyList_SetItem(result, part_idx, part) < 0) goto fail;
355    
356                            vertex_idx += length;
357                    }
358            }
359            else
360            {
361                    /* only one part. usual for SHPT_POINT */
362                    result = build_vertex_list(object, 0, object->nVertices, vertex_type);
363          }          }
     }  
364    
365      /* convert the list of parts */          return result;
366      part_start = 0;  
367      for (i = 0; i < num_parts; i++)  fail:
368      {          Py_XDECREF(part);
369          int j, length;          Py_DECREF(result);
370            return NULL;
         part = PySequence_GetItem(parts, i);  
         length = PySequence_Length(part);  
         part_starts[i] = part_start;  
   
         for (j = 0; j < length; j++)  
         {  
             tuple = PySequence_GetItem(part, j);  
             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;  
371  }  }
372    
 %}  
373    
374    /* Return the length coordinates of the shape object starting at vertex
375    * index as a Python-list of tuples. Helper function for
376    * SHPObject_vertices.
377    */
378    static PyObject* build_vertex_list(SHPObject *object, int index, int length, int vertex_type)
379    {
380            int i;
381            PyObject * list;
382            PyObject * vertex = NULL;
383    
384            list = PyList_New(length);
385            if (!list)
386                    return NULL;
387    
388  /*          for (i = 0; i < length; i++, index++)
389   * The SWIG Interface definition.          {
390   */                  switch (vertex_type)
391                    {
392                    case vtXY:
393                            vertex = Py_BuildValue("dd", object->padfX[index], object->padfY[index]);
394                            break;                  
395                    case vtXYM:
396                            vertex = Py_BuildValue("ddd", object->padfX[index], object->padfY[index],
397                                    object->padfM[index]);
398                            break;
399                    case vtXYZM:
400                            vertex = Py_BuildValue("dddd", object->padfX[index], object->padfY[index],
401                                    object->padfZ[index], object->padfM[index]);
402                            break;                  
403                    default:
404                            goto fail;
405                    }
406    
407  /* include some common SWIG type definitions and standard exception                  if (!vertex || PyList_SetItem(list, i, vertex) < 0) goto fail;
408     handling code */          }
409  %include typemaps.i          
410  %include exception.i          return list;
411    
412    fail:
413            Py_DECREF(list);
414            return NULL;
415    }
416    
417    
 /*  
  *  SHPObject -- Represents one shape  
  */  
418    
419  /* Exception typemap for the SHPObject constructor. The constructor the  static PyObject* shpobject_part_types(SHPObjectObject* self)
420     the wrapper function defined above which returns NULL in case of  {
421     error. */          int i;
422              PyObject* result = NULL;
423  %typemap(python,except) SHPObject*new_SHPObject {          SHPObject* object = self->shpObject;
424      $function;          
425      if (PyErr_Occurred())          if (object->nParts == 0 || object->panPartType == 0)
426            {
427                    Py_RETURN_NONE;
428            }
429            
430            result = PyTuple_New(object->nParts);
431            if (!result) return NULL;
432            
433            for (i = 0; i < object->nParts; ++i)
434            {
435                    /* PyTuple_SetItem steals a reference */
436                    PyObject* part_type = PyInt_FromLong((long)object->panPartType[i]);
437                    if (!part_type || PyTuple_SetItem(result, i, part_type) < 0) goto fail;
438            }      
439            return result;
440            
441    fail:
442            Py_DECREF(result);
443          return NULL;          return NULL;
444  }  }
445    
 /* 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.  
  */  
446    
 typedef struct {  
447    
448      /* The shape object has two read-only attributes: */  static PyObject* shpobject_type(SHPObjectObject* self, void* closure)
449    {
450            return PyInt_FromLong(self->shpObject->nSHPType);
451    }
452    
     /* The type of the shape. In the c-struct defined the field is  
      * called 'nSHPType' but for the python bindings 'type' is more  
      * appropriate.  
      */  
     %readonly %name(type) int nSHPType;  
   
     /* 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;  
453    
454    
455  /*  static PyObject* shpobject_id(SHPObjectObject* self, void* closure)
456   * ShapeFile --  Represents the shape file  {
457   */          return PyInt_FromLong(self->shpObject->nShapeId);
458    }
459    
 /* Here we do things a little different. We define a new C-struct that  
  * 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.  
  */  
460    
 /* First, define the C-struct */  
 %{  
     typedef struct {  
         SHPHandle handle;  
     } ShapeFile;  
 %}  
461    
462  /* define and use some typemaps for the info() method whose  /* return a string that can be feeded to eval() to reconstruct the object,
463   * C-implementation has four output parameters that are returned through   * assuming a proper context
  * 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:  
464   */   */
465    static PyObject* shpobject_repr(SHPObjectObject* self)
466  %apply int * OUTPUT { int * output_entities }  {
467  %apply int * OUTPUT { int * output_type }          PyObject* format = NULL;
468            PyObject* args = NULL;
469            PyObject* result = NULL;
470            
471            format = PyString_FromString("shapelib.SHPObject(%i, %i, %s, %s)");
472            if (!format) return NULL;
473    
474  /* for the last two, the 4-element arrays of min- and max-values, we          args = Py_BuildValue("iiNN",
475   * have to define our own typemaps:                  self->shpObject->nSHPType,
476   */                  self->shpObject->nShapeId,
477  %typemap (python,ignore) double * extents(double temp[4]) {                  shpobject_vertices(self),
478      $target = temp;                  shpobject_part_types(self));
479            if (!args)
480            {
481                    Py_DECREF(format);
482                    return NULL;
483            }
484            
485            result = PyString_Format(format, args);
486            Py_DECREF(args);
487            Py_DECREF(format);
488            return result;
489  }  }
490    
 %typemap (python,argout) double * extents {  
     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.  
  */  
491    
492    
493  %typemap(python,check) ShapeFile *{  static struct PyMethodDef shpobject_methods[] =
494      %#ifndef NOCHECK_$name  {
495      if (!$target || !$target->handle)          {"extents", (PyCFunction)shpobject_extents, METH_NOARGS,
496          SWIG_exception(SWIG_TypeError, "shapefile already closed");                  "extents() -> ((x_min, y_min, z_min, m_min), (x_max, y_max, z_max, m_max))\n\n"
497      %#endif                  "returns the 4D bounding box of the SHPObject"},
498  }          {"vertices", (PyCFunction)shpobject_vertices, METH_NOARGS,
499                    "vertices() ->  [[(x, y, ...), ...], ...]\n\n"
500  %{                  "Returns a list of object parts, where each part is again a list of vertices. "
501  #define NOCHECK_delete_ShapeFile                  "Each vertex is a tuple of two to four doubles, depending on the object type."},
502  #define NOCHECK_ShapeFile_close          {"part_types", (PyCFunction)shpobject_part_types, METH_NOARGS,
503  %}                  "part_types() -> tuple\n\n"
504                    "returns a tuple of integers, each integer indicating the type of the "
505  /* An exception handle for the constructor and the module level open()                  "corresponding part in vertices()"},
506   * and create() functions.          {NULL}
507   *  };
508   * Annoyingly, we *have* to put braces around the SWIG_exception()  
509   * calls, at least in the python case, because of the way the macro is  static struct PyGetSetDef shpobject_getsetters[] =
510   * written. Of course, always putting braces around the branches of an  {
511   * if-statement is often considered good practice.          {"type", (getter)shpobject_type, NULL, "type of the object (read-only)" },
512            {"id", (getter)shpobject_id, NULL, "id of the object (read-only)" },
513            {NULL}
514    };
515    
516    static PyTypeObject SHPObjectType = PYSHAPELIB_DEFINE_TYPE(SHPObjectObject, shpobject, "shapelib.SHPObject", 0);
517    
518    
519    /* --- ShapeFile ----------------------------------------------------------------------------------------------------- */
520    
521    typedef struct
522    {
523            PyObject_HEAD
524            SHPHandle handle;
525    }
526    ShapeFileObject;
527    
528    /* allocator
529   */   */
530  %typemap(python,except) ShapeFile * {  static PyObject* shapefile_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
531      $function;  {
532      if (!$source)          ShapeFileObject* self;  
533      {          self = (ShapeFileObject*) type->tp_alloc(type, 0);
534          SWIG_exception(SWIG_MemoryError, "no memory");          self->handle = NULL;
535      }          return (PyObject*) self;
     else if (!$source->handle)  
     {  
         SWIG_exception(SWIG_IOError, "$name failed");  
     }  
536  }  }
537    
538    /* destructor
539    */
540    static void shapefile_dealloc(ShapeFileObject* self)
541    {
542            SHPClose(self->handle);
543            self->ob_type->tp_free((PyObject*)self);
544    }
545    
546  /*  /* constructor
  * The SWIG-version of the ShapeFile struct.  
547   */   */
548    static int shapefile_init(ShapeFileObject* self, PyObject* args, PyObject* kwds)
549    {
550            char* file;
551            char* mode = "rb";
552            static char *kwlist[] = {"name", "mode", NULL};
553            if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|s:__init__", kwlist,
554                    Py_FileSystemDefaultEncoding, &file, &mode)) return -1;
555            
556            self->handle = SHPOpen(file, mode);
557            PyMem_Free(file);
558            
559            return self->handle ? 0 : -1;
560    }
561    
562  typedef struct  static PyObject* shapefile_close(ShapeFileObject* self)
563  {  {
564      /* Only methods and no attributes here: */          SHPClose(self->handle);
565      %addmethods {          self->handle = NULL;
566            Py_RETURN_NONE;
567    }
568    
569          /* The constructor. Takes two arguments, the filename and the  static PyObject* shapefile_info(ShapeFileObject* self)
570           * optinal mode which are passed through to SHPOpen (due to the  {
571           * renaming trick)          SHPHandle handle = self->handle;
572           */          return Py_BuildValue("ii(dddd)(dddd)",
573          ShapeFile(char *file, char * mode = "rb") {                          handle->nRecords, handle->nShapeType,
574              ShapeFile * self = malloc(sizeof(ShapeFile));                          handle->adBoundsMin[0], handle->adBoundsMin[1], handle->adBoundsMin[2], handle->adBoundsMin[3],
575              if (self)                          handle->adBoundsMax[0], handle->adBoundsMax[1], handle->adBoundsMax[2], handle->adBoundsMax[3]);
576                  self->handle = SHPOpen(file, mode);  }
577              return self;  
578          }  static PyObject* shapefile_read_object(ShapeFileObject* self, PyObject* args)
579    {
580          /* The destructor. Equivalent to SHPClose */          int index;
581          ~ShapeFile() {          SHPObject* object;
582              if (self->handle)          SHPObjectObject* result;
583                  SHPClose(self->handle);          
584              free(self);          if (!PyArg_ParseTuple(args, "i:read_object", &index)) return NULL;
585          }          
586            object = SHPReadObject(self->handle, index);    
587          /* close the shape file and set handle to NULL */          if (!object)
588          void close() {          {
589              if (self->handle)                  PyErr_SetString(PyExc_RuntimeError, "failed to read object");
590              {                  return NULL;
591                  SHPClose(self->handle);          }
592                  self->handle = NULL;          
593              }          result = PyObject_New(SHPObjectObject, &SHPObjectType);
594          }          if (!result)
595            {
596          /* info() -- Return a tuple (NUM_SHAPES, TYPE, MIN, MAX) where                  return PyErr_NoMemory();
597           * NUM_SHAPES is the number of shapes in the file, TYPE is the          }
598           * shape type and MIN and MAX are 4-element lists with the min.          
599           * and max. values of the data.          result->shpObject = object;
600           *          return (PyObject*) result;
601           * The arguments of the underlying shapelib function SHPGetInfo  }
602           * are all output parameters. To tell SWIG this, we have defined  
603           * some typemaps above  static PyObject* shapefile_write_object(ShapeFileObject* self, PyObject* args)
604           */  {
605          void info(int * output_entities, int * output_type,          int index, result;
606                    double * output_min_bounds, double *output_max_bounds) {          PyObject* object;
607              SHPGetInfo(self->handle, output_entities, output_type,          
608                         output_min_bounds, output_max_bounds);          if (!PyArg_ParseTuple(args, "iO:write_object", &index, &object)) return NULL;
609          }          
610            if (!PyObject_IsInstance(object, (PyObject*)&SHPObjectType))
611          /* Return object number i */          {
612          %new SHPObject * read_object(int i) {                  PyErr_SetString(PyExc_TypeError, "object is not a SHPObject");
613              return SHPReadObject(self->handle, i);                  return NULL;
614          }          }
615            
616          /* Write an object */          result = SHPWriteObject(self->handle, index, ((SHPObjectObject*)object)->shpObject);
617          int write_object(int iShape, SHPObject * psObject) {          if (result < 0)
618              return SHPWriteObject(self->handle, iShape, psObject);          {
619          }                  PyErr_SetString(PyExc_RuntimeError, "failed to write object");
620                    return NULL;
         /* Return the shapelib SHPHandle as a Python CObject */  
         PyObject * cobject() {  
             return PyCObject_FromVoidPtr(self->handle, NULL);  
621          }          }
622      }          return PyInt_FromLong((long)result);
623    }
624    
625  } ShapeFile;  static PyObject* shapefile_cobject(ShapeFileObject* self)
626    {
627            return PyCObject_FromVoidPtr(self->handle, NULL);
628    }
629    
630    static PyObject* shapefile_repr(ShapeFileObject* self)
631    {
632            /* TODO: it would be nice to do something like "shapelib.ShapeFile(filename, mode)" instead */
633            return PyString_FromFormat("<shapelib.ShapeFile object at %p>", self->handle);
634    }
635    
636  /*  static struct PyMethodDef shapefile_methods[] =
637   * Two module level functions, open() and create() that correspond to  {
638   * SHPOpen and SHPCreate respectively. open() is equivalent to the          {"close", (PyCFunction)shapefile_close, METH_NOARGS,
639   * ShapeFile constructor.                  "close() -> None\n\n"
640   */                  "close the shape file" },
641            {"info", (PyCFunction)shapefile_info, METH_NOARGS,
642                    "info() -> (num_shapes, type, (x_min, y_min, z_min, m_min), (x_max, y_max, z_max, m_max))\n\n"
643                    "returns info about ShapeFile with:\n"
644                    "- num_shapes: the number of the objects in the file\n"
645                    "- type: the type of the shape file (SHPT_POINT, SHPT_POLYGON, ...)\n"
646                    "- (x_min, ...), (x_max, ...): 4D bounding box of the data in the shape file" },
647            {"read_object", (PyCFunction)shapefile_read_object, METH_VARARGS,
648                    "read_object(id) -> SHPObject\n\n"
649                    "Returns shape indexed by id" },
650            {"write_object", (PyCFunction)shapefile_write_object, METH_VARARGS,
651                    "write_object(id, object) -> id\n\n"
652                    "Write an object at index id, and returns id."
653                    "If id == -1, the object is appended at the end of the shape file."},
654            {"cobject", (PyCFunction)shapefile_cobject, METH_NOARGS,
655                    "cobject() -> CObject\n\n"
656                    "Return the shapelib SHPHandle as a Python CObject"},
657            {NULL}
658    };
659    
660  %{  static struct PyGetSetDef shapefile_getsetters[] =
661      ShapeFile * open_ShapeFile(const char *filename, const char * mode) {  {
662          ShapeFile * self = malloc(sizeof(ShapeFile));          {NULL}
663          if (self)  };
664              self->handle = SHPOpen(filename, mode);  
665          return self;  static PyTypeObject ShapeFileType = PYSHAPELIB_DEFINE_TYPE(ShapeFileObject, shapefile, "shapelib.ShapeFile", 0);
     }  
 %}  
   
 %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.  
  */  
666    
667  %{  /* --- shapelib ------------------------------------------------------------------------------------------------------ */
668      static PyShapeLibAPI the_api = {  
669    static PyObject* shapelib_open(PyObject* module, PyObject* args)
670    {
671            return PyObject_CallObject((PyObject*)&ShapeFileType, args);
672    }
673    
674    static PyObject* shapelib_create(PyObject* module, PyObject* args)
675    {
676            char* file;
677            int type;
678            ShapeFileObject* result;
679            
680            if (!PyArg_ParseTuple(args, "eti:create", Py_FileSystemDefaultEncoding, &file, &type)) return NULL;
681            
682            result = PyObject_New(ShapeFileObject, &ShapeFileType);
683            if (!result)
684            {
685                    PyMem_Free(file);
686                    return PyErr_NoMemory();
687            }
688            
689            result->handle = SHPCreate(file, type);
690            PyMem_Free(file);
691            
692            if (!result->handle)
693            {
694                    PyObject_Del((PyObject*)result);
695                    PyErr_SetString(PyExc_RuntimeError, "Failed to create ShapeFile");
696                    return NULL;
697            }
698            
699            return (PyObject*) result;
700    }
701            
702    static PyShapeLibAPI shapelib_the_api =
703    {
704          SHPReadObject,          SHPReadObject,
705          SHPDestroyObject,          SHPDestroyObject,
706          SHPCreateTree,          SHPCreateTree,
707          SHPDestroyTree,          SHPDestroyTree,
708          SHPTreeFindLikelyShapes          SHPTreeFindLikelyShapes
709      };  };
   
     PyObject * c_api() {  
         return PyCObject_FromVoidPtr(&the_api, NULL);  
     }  
 %}  
710    
711  PyObject * c_api();  static PyObject* shapelib_c_api(PyObject* module)
712    {
713            return PyCObject_FromVoidPtr(&shapelib_the_api, NULL);
714  /*  }
  *  Module Level functions  
  */  
   
 /* convert shapefile types to names */  
 %name(type_name) const char *SHPTypeName(int nSHPType);  
 %name(part_type_name) const char *SHPPartTypeName(int nPartType);  
715    
716    static PyObject* shapelib_type_name(PyObject* module, PyObject* args)
717    {
718            int type;
719            if (!PyArg_ParseTuple(args, "i:type_name", &type)) return NULL;
720            return PyString_FromString(SHPTypeName(type));
721    }
722    
723  /*  static PyObject* shapelib_part_type_name(PyObject* module, PyObject* args)
724   * Finally, constants copied from shapefil.h  {
725   */          int type;
726            if (!PyArg_ParseTuple(args, "i:part_type_name", &type)) return NULL;
727            return PyString_FromString(SHPPartTypeName(type));
728    }
729    
730  /* -------------------------------------------------------------------- */  static struct PyMethodDef shapelib_methods[] =
731  /*      Shape types (nSHPType)                                          */  {
732  /* -------------------------------------------------------------------- */          {"open", (PyCFunction)shapelib_open, METH_VARARGS,
733  #define SHPT_NULL       0                  "open(name [, mode='rb']) -> ShapeFile\n\n"
734  #define SHPT_POINT      1                  "opens a ShapeFile" },
735  #define SHPT_ARC        3          {"create", (PyCFunction)shapelib_create, METH_VARARGS,
736  #define SHPT_POLYGON    5                  "create(name, type) -> ShapeFile\n\n"
737  #define SHPT_MULTIPOINT 8                  "creates a ShapeFile of a certain type (one of SHPT_POINT, SHPT_POLYGON)" },
738  #define SHPT_POINTZ     11          {"c_api", (PyCFunction)shapelib_c_api, METH_NOARGS,
739  #define SHPT_ARCZ       13                  "c_api() -> CObject\n\n"
740  #define SHPT_POLYGONZ   15                  "get C API of shapelib as a CObject" },
741  #define SHPT_MULTIPOINTZ 18          {"type_name", (PyCFunction)shapelib_type_name, METH_VARARGS,
742  #define SHPT_POINTM     21                  "type_name(type) -> string\n\n"
743  #define SHPT_ARCM       23                  "return type as string" },
744  #define SHPT_POLYGONM   25          {"part_type_name", (PyCFunction)shapelib_part_type_name, METH_VARARGS,
745  #define SHPT_MULTIPOINTM 28                  "part_type_name(part_type) -> string\n\n"
746  #define SHPT_MULTIPATCH 31                  "return part type as string" },
747            {NULL}
748    };
 /* -------------------------------------------------------------------- */  
 /*      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  
749    
750    PyMODINIT_FUNC initshapelib(void)
751    {
752            PyObject* module = Py_InitModule("shapelib", shapelib_methods);
753            if (!module) return;
754            
755            PYSHAPELIB_ADD_TYPE(SHPObjectType, "SHPObject");
756            PYSHAPELIB_ADD_TYPE(ShapeFileType, "ShapeFile");
757            
758            PYSHAPELIB_ADD_CONSTANT(SHPT_NULL);
759            PYSHAPELIB_ADD_CONSTANT(SHPT_POINT);
760            PYSHAPELIB_ADD_CONSTANT(SHPT_ARC);
761            PYSHAPELIB_ADD_CONSTANT(SHPT_POLYGON);
762            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPOINT);
763            PYSHAPELIB_ADD_CONSTANT(SHPT_POINTZ);
764            PYSHAPELIB_ADD_CONSTANT(SHPT_ARCZ);
765            PYSHAPELIB_ADD_CONSTANT(SHPT_POLYGONZ);
766            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPOINTZ);
767            PYSHAPELIB_ADD_CONSTANT(SHPT_POINTM);
768            PYSHAPELIB_ADD_CONSTANT(SHPT_ARCM);
769            PYSHAPELIB_ADD_CONSTANT(SHPT_POLYGONM);
770            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPOINTM);
771            PYSHAPELIB_ADD_CONSTANT(SHPT_MULTIPATCH);
772            PYSHAPELIB_ADD_CONSTANT(SHPP_TRISTRIP);
773            PYSHAPELIB_ADD_CONSTANT(SHPP_TRIFAN);
774            PYSHAPELIB_ADD_CONSTANT(SHPP_OUTERRING);
775            PYSHAPELIB_ADD_CONSTANT(SHPP_INNERRING);
776            PYSHAPELIB_ADD_CONSTANT(SHPP_FIRSTRING);
777            PYSHAPELIB_ADD_CONSTANT(SHPP_RING);
778    }
779    

Legend:
Removed from v.1611  
changed lines
  Added in v.2745

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26