Alireza Afzal Aghaei
Alireza Afzal Aghaei

Reputation: 1235

python: ImportError: dynamic module does not define module export function

im trying to install my function written in c (with python3 setup.py install) but python raise ImportError: dynamic module does not define module export function (PyInit_costFunction) error!

costFunction.c:

static PyObject *costFunction(PyObject *self, PyObject *args)
{
    return Py_BuildValue("d", 0); // or anything!
}

static PyMethodDef costFunction_methods[] = {
    {"costFunction", (PyCFunction)costFunction, METH_VARARGS, "cost function"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef costFunctionmodule = {
    PyModuleDef_HEAD_INIT,"costFunction", NULL, -1, costFunction_methods
};

PyMODINIT_FUNC PyInit_costFunction(void)
{
    return PyModule_Create(&costFunctionmodule);
}

setup.py:

from distutils.core import setup, Extension
setup(name='costFunction', version='1.0',  \
      ext_modules=[Extension('costFunction', ['costFunction.c'],include_dirs=['include'])])

external library: tinyexpr

i'm using linux mint 18 with python 3.5.2

EDIT: python3-dev version is 3.5.1-3

Upvotes: 2

Views: 3368

Answers (1)

Alireza Afzal Aghaei
Alireza Afzal Aghaei

Reputation: 1235

finally i used an dirty trick!

compiled c code(without python.h and any python datatype in C) with:

gcc -fPIC -Wall -O3 costFunction.c -o costFunction.so -shared  -fopenmp

and used python ctypes module to load and use it:

dll = ctypes.CDLL("./costFunction.so")
costFunction = dll.cost_function
costFunction.restype = ctypes.c_double
costFunction.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.c_int]

Upvotes: 1

Related Questions