~ubuntu-branches/ubuntu/karmic/python-scipy/karmic

« back to all changes in this revision

Viewing changes to Lib/sparse/_superlu_utils.c

  • Committer: Bazaar Package Importer
  • Author(s): Daniel T. Chen (new)
  • Date: 2005-03-16 02:15:29 UTC
  • Revision ID: james.westby@ubuntu.com-20050316021529-xrjlowsejs0cijig
Tags: upstream-0.3.2
ImportĀ upstreamĀ versionĀ 0.3.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
#include "Python.h"
 
3
#include <setjmp.h>
 
4
 
 
5
jmp_buf _superlu_py_jmpbuf;
 
6
PyObject *_superlumodule_memory_dict=NULL;
 
7
 
 
8
/* Abort to be used inside the superlu module so that memory allocation 
 
9
   errors don't exit Python and memory allocated internal to SuperLU is freed.
 
10
   Calling program should deallocate (using SUPERLU_FREE) all memory that could have 
 
11
   been allocated.  (It's ok to FREE unallocated memory)---will be ignored.
 
12
*/
 
13
 
 
14
void superlu_python_module_abort(char *msg)
 
15
{
 
16
  PyErr_SetString(PyExc_RuntimeError, msg);
 
17
  longjmp(_superlu_py_jmpbuf, -1);
 
18
}
 
19
 
 
20
void *superlu_python_module_malloc(size_t size)
 
21
{
 
22
  PyObject *key=NULL;
 
23
  long keyval;
 
24
  void *mem_ptr; 
 
25
 
 
26
  if (_superlumodule_memory_dict == NULL) {
 
27
    _superlumodule_memory_dict = PyDict_New();
 
28
  }
 
29
  mem_ptr = malloc(size);
 
30
  if (mem_ptr == NULL) return NULL;
 
31
  keyval = (long) mem_ptr;
 
32
  key = PyInt_FromLong(keyval);
 
33
  if (key == NULL) goto fail;
 
34
  if (PyDict_SetItem(_superlumodule_memory_dict, key, Py_None)) goto fail;
 
35
  Py_DECREF(key);
 
36
  return mem_ptr;
 
37
 
 
38
 fail:
 
39
  Py_XDECREF(key);
 
40
  free(mem_ptr);
 
41
  superlu_python_module_abort("superlu_malloc: Cannot set dictionary key value in malloc.");
 
42
  return NULL;
 
43
 
 
44
}
 
45
 
 
46
void superlu_python_module_free(void *ptr)
 
47
{
 
48
  PyObject *key;
 
49
  long keyval;
 
50
  PyObject *ptype, *pvalue, *ptraceback;
 
51
 
 
52
  if (ptr == NULL) return;
 
53
  PyErr_Fetch(&ptype, &pvalue, &ptraceback);
 
54
  keyval = (long )ptr;
 
55
  key = PyInt_FromLong(keyval);
 
56
  /* This will only free the pointer if it could find it in the dictionary
 
57
     of already allocated pointers --- thus after abort, the module can free all
 
58
     the memory that "might" have been allocated to avoid memory leaks on abort 
 
59
     calls.
 
60
   */ 
 
61
  if (!(PyDict_DelItem(_superlumodule_memory_dict, key))) {
 
62
    free(ptr);
 
63
  }
 
64
  Py_DECREF(key);
 
65
  PyErr_Restore(ptype, pvalue, ptraceback);
 
66
  return; 
 
67
}
 
68