Python C API: Passing two functions of many parameters with special types as module

720 views Asked by At

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);
}
1

There are 1 answers

3
tynn On BEST ANSWER

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.