Calling C Function Pointers from Python

shochet at my-deja.com shochet at my-deja.com
Sat Jul 29 01:44:23 EDT 2000


I am currently in the middle of hooking up a large external C++ library by
maintaining a database of C++ function pointers that I will call from Python.
If anybody has tried this before, my question is: Is there a good way to call
these function pointers without having to wrap every single one in a Python-C
module? The only package I know of that might do this job is libffi, but it
only runs on Unix, not on Windows.

Has anybody tried this approach before? I have investigated SWIG, but cannot
use it because the C++ library uses lots of fancy C++ features (templates,
etc) that make it cranky.

Currently my idea is to auto-generate all these function pointer wrappers
with code that looks something like this:

  // Original C++ funcion (a simplified example)
  int add(int a, int b) {return a+b};

  // Wrapped generated Python C function in a module I will import
  static PyObject *_internal_add(PyObject *self, PyObject *args) {
    typedef int (*FUNC1)(int, int);
    FUNC1 _arg0;
    int  _arg1,  _arg2, _result;
    PyObject * _resultObj, _argo0;
    if(!PyArg_ParseTuple(args,"Oii",&_argo0,&_arg1,&_arg2))
	return NULL;
    _arg0 = (FUNC1)PyCObject_AsVoidPtr(_argo0);
    _result = (int)(_arg0(_arg1, _arg2));
    _resultObj = Py_BuildValue("i", _result);
    return _resultObj;
    }

  # I will then call this by passing in the function pointer and arguments
from Python.  def add(a, b):  function_pointer =
lookup_global_function('add')  returnValue = _internal_add(function_pointer,
a, b)  return returnValue

Thanks for any opinions/suggestions.
 -- Joe (shochet at hotmail.com)


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list