【发布时间】:2016-04-03 21:47:09
【问题描述】:
我的问题如下: 我想从我的 Python 文件中调用一个 C 函数并将一个值返回给该 Python 文件。 我尝试了以下在 Python 中使用嵌入式 C 的方法(以下代码是名为“mod1.c”的 C 代码)。我使用的是 Python3.4,因此格式遵循文档指南中给出的格式。当我调用时出现问题我的设置文件(下面的第二个代码)。 #包括 #include "sum.h"
static PyObject*
mod_sum(PyObject *self, PyObject *args)
{
int a;
int b;
int s;
if (!PyArg_ParseTuple(args,"ii",&a,&b))
return NULL;
s = sum(a,b);
return Py_BuildValue("i",s);
}
/* DECLARATION OF METHODS */
static PyMethodDef ModMethods[] = {
{"sum", mod_sum, METH_VARARGS, "Descirption"}, // {"methName", modName_methName, METH_VARARGS, "Description.."}, modName is name of module and methName is name of method
{NULL,NULL,0,NULL}
};
// Module Definition Structure
static struct PyModuleDef summodule = {
PyModuleDef_HEAD_INIT,
"sum",
NULL,
-1,
ModMethods
};
/* INITIALIZATION FUNCTION */
PyMODINIT_FUNC initmod(void)
{
PyObject *m;
m = PyModule_Create(&summodule);
if (m == NULL)
return m;
}
安装程序.py from distutils.core 导入设置,扩展
setup(name='buildsum', version='1.0', \
ext_modules=[Extension('buildsum', ['mod1.c'])])
我使用 gcc 编译代码时得到的结果是以下错误:Cannot export PyInit_buildsum: symbol not defined
我将非常感谢您对此问题的任何见解或帮助,或有关如何从 Python 调用 C 的任何建议。谢谢!
---------------------------编辑 ------- -------------------------- 感谢cmets: 我现在尝试了以下方法:
static PyObject*
PyInit_sum(PyObject *self, PyObject *args)
{
int a;
int b;
int s;
if (!PyArg_ParseTuple(args,"ii",&a,&b))
return NULL;
s = sum(a,b);
return Py_BuildValue("i",s);
}
对于第一个函数;但是,我仍然遇到 PyInit_sum: symbol not defined
的相同错误【问题讨论】:
-
symbol not defined:函数 PyInit_buildsum 不存在。在您的 .c 中,您不必将“sum”更改为“buildsum”吗? -
您好,感谢您的回复。如果我将 buildsum 更改为 sum(在设置文件中),我会得到同样的错误,只是名称为 "PyInit_sum:symbol not defined"
-
是这样的:
mod_sum应该命名为PyInit_sum,或者有一个宏PYINIT(mod_sum)什么的可以使用,而不是写mod_sum。 -
您的
initmod应称为PyInit_sum或PyInit_buildsum,具体取决于您希望调用的入口点。应该返回PyModule_Create的返回值,NULL的测试是错误的。 -
@cdarke:谢谢!!我试过了(用我的原始代码),它奏效了。
标签: python c integration