Search code examples
pythoncmultiple-languages

Calling a C function through Python - after compilation


In an attempt to call a c function from Python, (in a previous post Calling a C function from a Python file. Getting error when using Setup.py file), I have compiled the code into a .pyd file and am testing the program. However, I am coming across the error

AttributeError: 'module' object has no attribute 'addTwo'

My test file is as so:

import callingPy
a = 3
b = 4
s = callingPy.addTwo(a, b)
print("S", s)

Where callingPy is the following .c file (turned into a .pyd) through compilation:

#include <Python.h>
#include "adder.h"

static PyObject* adder(PyObject *self, PyObject *args)       
{
    int a;
    int b;
    int s;
    if (!PyArg_ParseTuple(args,"ii",&a,&b))                      
       return NULL;
    s = addTwo(a,b);                                                
    return Py_BuildValue("i",s);                                
}

/* DECLARATION OF METHODS*/
static PyMethodDef ModMethods[] = {
    {"modsum", adder, METH_VARARGS, "Descirption"},         
    {NULL,NULL,0,NULL}
};

// Module Definition Structure
static struct PyModuleDef summodule = {
   PyModuleDef_HEAD_INIT,"modsum", NULL, -1, ModMethods     
};

/* INITIALIZATION FUNCTION*/
PyMODINIT_FUNC PyInit_callingPy(void)
{
    PyObject *m;
    m = PyModule_Create(&summodule);
    return m; 
}

Any help would be greatly appreciated! Thank you.


Solution

  • The only function in the extension module is exported to Python under the name modsum. You called addTwo. This seems self-explanatory.

    It looks like at the C layer, there is a raw C function named addTwo that does the work for the C function adder, which is then exported to Python under the name modsum. So you should either rename the export, or call it with the correct name:

    s = callingPy.modsum(a, b)
    

    It looks like you copy-pasted a skeleton extension module, switched one tiny internal, and didn't fix up any of the exports or names.