作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试为 python 编写一个 C 扩展。使用代码(如下)我得到编译器警告:
implicit declaration of function ‘Py_InitModule’
它在运行时失败并出现此错误:
undefined symbol: Py_InitModule
我花了好几个小时寻找一个没有乐趣的解决方案。我已经尝试了对语法的多次细微更改,我什至发现了一个帖子表明该方法已被弃用。但是我找不到替代品。
代码如下:
#include <Python.h>
//a func to calc fib numbers
int cFib(int n)
{
if (n<2) return n;
return cFib(n-1) + cFib(n-2);
}
static PyObject* fib(PyObject* self,PyObject* args)
{
int n;
if (!PyArg_ParseTuple(args,"i",&n))
return NULL;
return Py_BuildValue("i",cFib(n));
}
static PyMethodDef module_methods[] = {
{"fib",(PyCFunction) fib, METH_VARARGS,"calculates the fibonachi number"},
{NULL,NULL,0,NULL}
};
PyMODINIT_FUNC initcModPyDem(void)
{
Py_InitModule("cModPyDem",module_methods,"a module");
}
如果有帮助,这里是我的 setup.py :
from distutils.core import setup, Extension
module = Extension('cModPyDem', sources=['cModPyDem.c'])
setup(name = 'packagename',
version='1.0',
description = 'a test package',
ext_modules = [module])
以及 test.py 中的测试代码:
import cModPyDem
if __name__ == '__main__' :
print(cModPyDem.fib(200))
任何帮助将不胜感激。
最佳答案
您的代码在 Python 2.x 中可以正常工作,但是 Py_InitModule
在 Python 3.x 中不再使用。如今,您创建了 PyModuleDef
结构,然后将对它的引用传递给 PyModule_Create
.
结构如下:
static struct PyModuleDef cModPyDem =
{
PyModuleDef_HEAD_INIT,
"cModPyDem", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
module_methods
};
然后是你的 PyMODINIT_FUNC
函数看起来像:
PyMODINIT_FUNC PyInit_cModPyDem(void)
{
return PyModule_Create(&cModPyDem);
}
注意 PyMODINIT_FUNC
的名称函数的格式必须为 PyInit_<name>
在哪里 <name>
是您的模块的名称。
如果您阅读 Extending,我认为这将是值得的在 Python 3.x 文档中。它详细描述了如何在现代 Python 中构建扩展模块。
关于python - 编译器找不到 Py_InitModule() .. 它是否已被弃用,如果是,我应该使用什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305731/
我是一名优秀的程序员,十分优秀!