c bindings

Sebastien Loisel loisel at math.mcgill.ca
Fri Jul 6 16:25:21 EDT 2001


Hello.

I apologize in advance, for I have already asked help from help at python.org
for this very same problem. I didn't know about this newsgroup.

I am writing an extension module. For this purpose, I have written a very
short code generator, to create wrappers around my C library. For some
simple test cases, it seems to work fine, but I am encountering core dumps
with a more complete program. I don't think this is relevant, but I'm
running python 1.5.2 in Linux. As I see it, I can either work hard and
figure it out myself, but the fastest would probably be for a guru to tell
me what I'm doing wrong. Of course, I hate looking at someone else's code
just as much as the next guy, so I've had my code generator create the
shortest useful binding I can have it generate, to see if there are any
errors in that.

If you guys could tell me if I've got a refcount wrong in there somewhere, I
would appreciate greatly. I would also appreciate if you would cc my email
address in your replies, for reference purposes in the future.

Thank you very much,

Sebastien Loisel

------snip here-----
#include <Python.h>
static PyObject *ErrorObject;
// This code is automatically generated
/* This function takes for argument a sequence of ints and returns
   a list of floats. */
static PyObject *example_py(PyObject *self, PyObject *args)
{
  int j;
  PyObject *_;
  float *ret;
  int ret_size=-1;
  PyObject *ret_list;
  int *param;
  int param_size;
  PyObject *param_helper;
  if(!PyArg_ParseTuple(args,"O", &param_helper)) return 0;
  if(!PySequence_Check(param_helper)) {
    PyErr_SetString(ErrorObject,"arg should be a sequence");
    return 0;
  }
  param_size=PySequence_Length(param_helper);
  param=gtc_must_malloc(param_size*sizeof(int));
  for(j=0;j<param_size;j++) {
    _=PySequence_GetItem(param_helper,j);
    param[j]=PyInt_AsLong(_);
    Py_DECREF(_);
  }
  ret_size=param_size;
  ret=gtc_must_malloc(sizeof(float)*ret_size);
  for(j=0;j<ret_size;j++) ret[j]=param[j]+j/2.0;
  if(ret_size<0) abort();
  ret_list=PyList_New(ret_size);
  for(j=0;j<ret_size;j++) {
    PyList_SetItem(ret_list,j,PyFloat_FromDouble(ret[j]));
  }
  free(ret);
  return ret_list;
}
static PyMethodDef example_methods[] = {
  {"example",example_py,1},
  {0,0} // sentinel
};
DL_EXPORT(void) initexample()
{
  PyObject *m,*d;
  m=Py_InitModule("example",example_methods);
  d=PyModule_GetDict(m);
  ErrorObject = PyErr_NewException("example.error",0,0);
  PyDict_SetItemString(d,"error",ErrorObject);
}






More information about the Python-list mailing list