1

I am attempting to create a Python module using C. This module has two callable functions - one with mpi support and one without.

int run_mymodule(char *file1, char *file2, char *file3, PyObject *tmpp)
{
  <internal actions, returns int indicating return status>
}

int run_mymodule_with_mpi(char *file1, int &_mpi, char *file2, char *file3, PyObject *tmpp)
{
  <internals, returns int>
}

Using boost, this was trivial to connect to a module (using BOOST_PYTHON_MODULE). However, this is proving to be more challenging using purely the python-c api. I have tried my best to create a propper interface for python, however it is not working. Here is my attempt at interfacing the C functions to python as a module. How is my approach incorrect? Where do I go from here?

static PyMethodDef myModule_methods[] = {
    {"run_mymodule", run_mymodule, METH_VARARGS},
    {"run_mymodule_with_mpi", run_mymodule_with_mpi, METH_VARARGS},
    {NULL, NULL}
    };

void initmyModule(void)
{
    (void) Py_InitModule("myModule", myModule_methods);
}
kilojoules
  • 9,768
  • 18
  • 77
  • 149

1 Answers1

2

The PyCFunction type is defined as

typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);

So you need wrap your functions with a real PyCFunction first. You could use the following as simple template of how to start with it:

static PyObject * wrap_run_mymodule(PyObject *, PyObject *args) {
    char *file1, *file2, *file3;
    PyObject *tmpp;
    if(!PyArg_ParseTuple(args, "sssO", &file1, &file2, &file3, &tmpp))
        return NULL;
    return Py_BuildValue("i", run_mymodule(file1, file2, file3, tmpp));
}

static PyMethodDef myModule_methods[] = {
    {"run_mymodule", (PyCFunction) wrap_run_mymodule, METH_VARARGS},
    {NULL, NULL}
};

Also see PyArg_ParseTuple to find better formats for your arguments. Especially the file[123] variables should be of const char * here.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • Is there a simple way to parse an MPI_Comm object? `PyArg_ParseTuple(args, "s_ssO", &file1, &_mpi, &file2, &file3, &tmpp))` – kilojoules Jun 24 '15 at 19:01
  • I don't know anything about MPI_Comm but maybe `O!` or `O&` could be used for that. – tynn Jun 24 '15 at 20:07
  • Thanks for the great answer! I followed your advise and am now stuck on a `bad_alloc` error which I have started a new question for [here](http://stackoverflow.com/questions/31077040/stdbad-alloc-error-without-cout-works-when-i-print-variables) – kilojoules Jun 26 '15 at 17:08