[MATRIX-SIG] NumPy external library wrapping help

Johann Hibschman johann@physics.berkeley.edu
Wed, 11 Mar 1998 15:29:23 -0800


"Lorenzo M. Catucci" <lorenzo@argon.roma2.infn.it> wrote:
> 
> Now, the questions: I'd like to wrap a couple of PORT least sqares 
> routines for use within Python's numeric framework, and therefore I'll
> need to do a couple of things:
> 1. make fortran arrays - seems simple: make C ones, and then access them 
>    `backwards' (read, via transposed indexes). The only problem will be
>    the malloc/free one.

Have you tried looking at modules like lapack_litemodule.c in the
distribution?  They should give some examples.

> 2. Put in callback support - this is what I fear: on one hand, I'll need
>    to be able to call the python interpreter, then I'll have to validate 
>    the called functions for output format and the like, and further make
>    sure the environment the callbacks will be executed in is the right one
>    (what happens if the user calls for `sin(x)'?)

This is tougher.

I haven't actually done this, but I have a few ideas.  The most
obvious thing you could do is make a "trampoline" function like:

/* I forget all the actual python function calls---you'll have to
check the documentation.  I tend to use Mark Lutz's Programming Python
book as a ref. */

/* global pointer to put the python object into: make this a python
LIST, so you can store multiple functions (use the list as a stack) */
PyObject *foo_function_list;

static double foo_trampoline(double x)
{
  [convert x into a PyObject => py_x];
  [get foo_function_list[0] => py_function]  /* first item on stack */
  [call py_function on py_x => py_answer];
  [convert py_answer into a double => answer];
  return answer;
}

static PyObject *wrap_foo(...)
{
  [extract the python function object py_function to be passed to C];

  /* set the global pointer */
  [append py_function to foo_function_list (push onto stack)]
  /* pass the C (or fortran) routine the trampoline function */
  answer = foo(foo_trampoline, ...);
  [pop py_function off foo_function_list]

  [convert answer to c => py_answer]
  return py_answer;
}

I hope that helps with the idea at least; I can't provide more details
at this point.

Calling the python function is likely to be slow slow slow, which is
why I've never actually done this.  If you get it running, I'd like to
hear about how the performance is.

I'd like to hear what anyone else thinks about this.

- Johann
-- 
Johann Hibschman              |    Grad Student, UC Berkeley Astronomy
johann@physics.berkeley.edu   |    http://astro.berkeley.edu/~johann

_______________
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
_______________