问题描述
在第二次调用以下代码时,我的应用程序段错误,所以我想我遗漏了一些东西:
Py_Initialize();pName = PyString_FromString("comp_macbeth");pModule = PyImport_Import(pName);Py_DECREF(pName);如果(pModule == NULL){PyErr_Print();Py_Finalize();返回;}pFunc = PyObject_GetAttrString(pModule, "计算");/* pFunc 是一个新的引用 */如果 (!pFunc || !PyCallable_Check(pFunc) ) {PyErr_Print();Py_Finalize();返回;}Py_Finalize();
comp_macbeth.py 正在导入 numpy.如果我删除 numpy 导入,一切都很好.这是一个 numpy 错误,还是我遗漏了一些关于进口的东西?
来自 Py_Finalize 文档:
如果多次调用初始化例程,某些扩展可能无法正常工作;如果应用程序多次调用 Py_Initialize() 和 Py_Finalize() 就会发生这种情况.
显然 Numpy 就是其中之一.另请参阅 Numpy-discussion 的此消息.>
只调用一次 Py_Initialize()
,并在退出时清理,是要走的路.(而且它也应该更快!)
On the second call of the following code, my app segfault, so I guess I am missing something :
Py_Initialize();
pName = PyString_FromString("comp_macbeth");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if(pModule == NULL) {
PyErr_Print();
Py_Finalize();
return;
}
pFunc = PyObject_GetAttrString(pModule, "compute");
/* pFunc is a new reference */
if (!pFunc || !PyCallable_Check(pFunc) ) {
PyErr_Print();
Py_Finalize();
return;
}
Py_Finalize();
The comp_macbeth.py is importing numpy. If I remove the numpy import, everything is fine. Is it a numpy bug, or am I missing something about imports ?
From the Py_Finalize docs:
Apparently Numpy is one of those. See also this message from Numpy-discussion.
Calling Py_Initialize()
only once, and cleaning up at exit, is the way to go. (And it's should be faster, too!)
这篇关于Py_initialize/Py_Finalize 不能与 numpy 一起工作两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!