File: widget.i

package info (click to toggle)
swig 1.1p5-1
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 9,448 kB
  • ctags: 5,025
  • sloc: cpp: 21,599; ansic: 13,333; yacc: 3,297; python: 2,794; makefile: 2,197; perl: 1,984; tcl: 1,583; sh: 736; lisp: 201; objc: 143
file content (85 lines) | stat: -rw-r--r-- 2,310 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// SWIG Module for handling some callback functions written in Python

%module callback
%{

#include "widget.h"

%}

/* These are some normal C functions for our "widget."       */
/* Note : use of a typedef for function pointers is required */

typedef double (*CALLBACK)(double, void *);
Widget *new_widget();
double  widget_op(Widget *w, double a);
void    widget_add_callback(Widget *w, CALLBACK callback, void *);

// ----------------------------------------------------------------
// Python helper functions for adding callbacks
// ----------------------------------------------------------------

%{

/* This function matches the prototype of a normal C callback
   function for our widget. However, the clientdata pointer
   actually refers to a Python callable object. */

static double PythonCallBack(double a, void *clientdata)
{
   PyObject *func, *arglist;
   PyObject *result;
   double    dres = 0;
   
   func = (PyObject *) clientdata;
   arglist = Py_BuildValue("(d)",a);
   result = PyEval_CallObject(func,arglist);
   Py_DECREF(arglist);
   if (result) {
     dres = PyFloat_AsDouble(result);
   }
   Py_XDECREF(result);
   return dres;
}

/* This function adds a new Python function object as a callback object */

static void pywidget_add_callback(Widget *w, PyObject *PyFunc) {
  widget_add_callback(w,PythonCallBack, (void *) PyFunc);
  Py_INCREF(PyFunc);
}

%}

// -------------------------------------------------------------------
// SWIG typemap allowing us to grab a Python callable object
// -------------------------------------------------------------------

%typemap(python,in) PyObject *PyFunc {
  if (!PyCallable_Check($source)) {
      PyErr_SetString(PyExc_TypeError, "Need a callable object!");
      return NULL;
  }
  $target = $source;
}

// Our new python callback registration function.  Note the use of 
// a typemap to grab a PyObject.

void pywidget_add_callback(Widget *w, PyObject *PyFunc);

// Now make a symbol for our C callback function
%{
/* Need to declare it in our file */
extern double foo(double, void *);
%}

// Create a constant 'FOO' that is the address of a C callback function
const CALLBACK FOO = foo;

// C function for filling an array
extern void fill_array(Widget *w, double *data, int nitems);

// Grab SWIG array module
%include array.i