Python:在扩展模块中引用使用 PyErr_NewException 创建的异常类 [英] Python: Referring to an Exception Class Created with PyErr_NewException in an Extension Module
问题描述
我正在创建自己的 Python 扩展(使用 SWIG,但我希望这无关紧要).
I am creating my own Python extension (using SWIG, but I hope that is not relevant).
在 C++ 方面,我使用 PyErr_NewException 创建自定义异常对象.
In the C++ side of it, I am using PyErr_NewException to create a custom exception object.
// C++ - create a custom Python Exception class.
m = Py_InitModule((char *) "MyModule", SwigMethods);
g_pyMyErr = PyErr_NewException( "MyModule.MyErr", 0, 0 );
Py_INCREF(g_pyMyErr);
int result = PyModule_AddObject(m, "MyErr", g_pyMyErr);
上面的代码返回成功值,我可以成功抛出上面的异常并在Python客户端代码中捕获它.
The above code returns success values and I can throw the above exception successfully and catch it in the Python client code.
问题是这样的:当我在 Python 代码中提到MyErr"时,我收到一条错误消息,指出MyErr"未定义.
The problem is this: When I refer to "MyErr" in Python code I get an error saying "MyErr" is not defined.
// Python client code - catch the exception
from MyModule import *
try:
causeException()
catch MyErr: # Error: MyErr is not defined.
pass
catch Exception:
pass
我目前的想法是 SWIG 可能正在改变(修改)事物的名称.
My current thinking is that maybe SWIG is altering (mangling) the names of things.
推荐答案
你需要定义错误然后:
%{
class MyErr {};
%}
另外,我建议添加这个,以便您可以将异常捕获为 MyModule.MyErr 而不是 MyModule._MyModule.MyErr(因为它们将是由 SWIG 生成的):
Also, I would suggest adding this, so that you could catch the exceptions as MyModule.MyErr and not as MyModule._MyModule.MyErr (since that is how they will be generated by SWIG):
%pythoncode %{
MyErr = _MyModule.MyErr
%}
这篇关于Python:在扩展模块中引用使用 PyErr_NewException 创建的异常类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!