问题描述
我正在尝试为python编写C扩展名.通过下面的代码,我得到了编译器警告:
I am attempting to write a C extension for python. With the code (below) I get the compiler warning:
implicit declaration of function ‘Py_InitModule’
它在运行时由于以下错误而失败:
And it fails at run time with this error:
undefined symbol: Py_InitModule
我花了数小时来寻找解决方案,但并没有感到高兴.我尝试对语法进行多次细微更改,甚至发现一则帖子表明该方法已被弃用.但是我找不到替代品.
I have spent literally hours searching for a solution with no joy. I have tried multiple minor changes to syntax, I even found a post suggesting the method has been deprecated. However I find no replacement.
这是代码:
#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:
If it helps here is my 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中的测试代码:
And the test code in test.py :
import cModPyDem
if __name__ == '__main__' :
print(cModPyDem.fib(200))
任何帮助将不胜感激.
推荐答案
您拥有的代码在Python 2.x中可以正常工作,但是Py_InitModule
在Python 3.x中不再使用.如今,您创建了一个 PyModuleDef
结构,然后将对其传递引用到 PyModule_Create
.
The code you have would work fine in Python 2.x, but Py_InitModule
is no longer used in Python 3.x. Nowadays, you create a PyModuleDef
structure and then pass a reference to it to 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
函数如下所示:
And then your PyMODINIT_FUNC
function would look like:
PyMODINIT_FUNC PyInit_cModPyDem(void)
{
return PyModule_Create(&cModPyDem);
}
请注意,PyMODINIT_FUNC
函数的名称必须采用PyInit_<name>
的形式,其中<name>
是模块的名称.
Note that the name of the PyMODINIT_FUNC
function must be of the form PyInit_<name>
where <name>
is the name of your module.
如果您阅读Python 3.x文档中的扩展,我认为这是值得的.它详细介绍了如何在现代Python中构建扩展模块.
I think it would be worthwhile if you read Extending in the Python 3.x documentation. It has a detailed description of how to build extension modules in modern Python.
这篇关于编译器找不到Py_InitModule()..是否已弃用,如果可以,我应该使用什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!