Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: dynamic module does not define init function

Tags:

c++

python

I am trying to reproduce the following tutorial https://csl.name/post/c-functions-python/.

My Python extension in C++ looks like:

#include <Python.h>

static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
  char *s = "Hello from C!";
  return Py_BuildValue("s", s);
}

static PyObject* py_myOtherFunction(PyObject* self, PyObject* args)
{
  double x, y;
  PyArg_ParseTuple(args, "dd", &x, &y);
  return Py_BuildValue("d", x*y);
}

static PyMethodDef extPy_methods[] = {
  {"myFunction", py_myFunction, METH_VARARGS},
  {"myOtherFunction", py_myOtherFunction, METH_VARARGS},
  {NULL, NULL}
};

void initextPy(void)
{
  (void) Py_InitModule("extPy", extPy_methods);
}

I am using the following setup.py:

from distutils.core import setup, Extension
setup(name='extPy', version='1.0',  \
ext_modules=[Extension('extPy', ['extPy.cpp'])])

After invoking it with python setup.py install the .so file seems to be in the right place.

But when I try to use this extension with import extPy I get the Error:

ImportError: dynamic module does not define init function

What am I missing here? Thanks for Help.

like image 478
P Alcove Avatar asked Jan 20 '15 08:01

P Alcove


1 Answers

Because the function initextPy is a C++ function which causes the C++ compiler to mangle the name so it's not recognizable.

You need to mark the function as extern "C" to inhibit the name mangling:

extern "C" void initextPy(void)
{
    ...
}
like image 145
Some programmer dude Avatar answered Oct 29 '22 14:10

Some programmer dude