【问题标题】:python: ImportError: dynamic module does not define module export functionpython:ImportError:动态模块未定义模块导出功能
【发布时间】:2016-08-18 00:22:50
【问题描述】:

我试图安装我用 c 编写的函数(使用 python3 setup.py install)但是 python 引发 ImportError: dynamic module does not defined module export function (PyInit_costFunction) 错误!

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'])])

外部库:tinyexpr

我正在使用 linux mint 18 和 python 3.5.2

编辑: python3-dev版本是3.5.1-3

【问题讨论】:

    标签: python-3.x importerror python-c-extension


    【解决方案1】:

    最后我用了一个肮脏的把戏!

    编译的c代码(没有python.h和C中的任何python数据类型):

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

    并使用python ctypes模块来加载和使用它:

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

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 2020-05-06
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多