问题描述
您好,我正在使用python扩展模块。目前我正在努力解决无效的静态全局变量 HiveError
。以下是代码片段:
我的扩展模块头文件:
Hello, I am working on python extension module. Currently I'm struggling with invalid static global variable HiveError
. Here are code snippets:
My extension module header file:
...
#ifdef _DEBUG
#define _DEBUG_BUILD 1
#undef _DEBUG
#endif
#ifdef __cplusplus
extern "C"
{
#endif
#include <Python.h>
#include <structmember.h>
static PyObject * HiveError;
#ifdef __cplusplus
}
#endif
...
这是 PyMODINIT_FUNC
函数初始化 HiveError
例外:
And this is PyMODINIT_FUNC
function initializing HiveError
exception:
PyMODINIT_FUNC PyInit_pphive(void)
{
PyObject * module;
if(!init_type(&PyHive_Type))
{
return NULL;
}
module = PyModule_Create(&PPHiveModule);
if (module == NULL ||
!add_type(module, &PyHive_Type, "Hive"))
{
return NULL;
}
// init exception
HiveError = PyErr_NewException("pphive.HiveError", PyExc_Exception, NULL);
if(!HiveError)
return NULL;
Py_INCREF(HiveError);
if(PyModule_AddObject(module, "HiveError", HiveError) == -1)
return NULL;
return module;
}
在上面的函数中, HiveError
是有效的 - 可以抛出python代码...然后是python代码,它实例化 Hive
类并调用它的方法,我想抛出异常:
.py代码
In above function, HiveError
is valid - can be thrown to python code... Then comes python code, which instantiates Hive
class and call its method, where I want exception to be throw:
.py code
hive = pphive.Hive(path)
hive.expand()
我的展开
功能:
My expand
function:
static PyObject * expand(PyHive * self, PyObject * args)
{
Py_INCREF(HiveError); // access violation
return PyErr_Format(HiveError, ""); // throws SystemError: error return without exception set
};
HiveError
在我的 expand
函数中为NULL ,为什么?我基本上把整个代码放在异常初始化和扩展函数之间调用。
任何提示或建议可能会删除异常?
HiveError
is NULL in my expand
function, why? I've put basically whole code called between exception initializing and expand function.
Any tips, or suggestions where exception might be deleted?
推荐答案
static PyObject * HiveError;
但它应该是:
but it should be:
extern PyObject * HiveError;
然后在您的主模块(具有初始化代码的模块)中,您应该在开头添加以下语句:
Then in your main module (the one with the initialisation code), you should add the following statement at the beginning:
PyObject * HiveError = NULL;
来创建实际的指针变量。
to create the actual pointer variable.
这篇关于Python C ++模块异常问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!