Boost.Python自定义异常类 [英] Boost.Python custom exception class

查看:97
本文介绍了Boost.Python自定义异常类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Boost.Python实现了一个Python扩展模块。模块应该定义自己的继承 Exception 的自定义异常类。

I'm implementing a Python extension module using Boost.Python. The module should define its own custom exception classes that inherit Exception. How do I do that?

推荐答案

以下函数创建一个新的Python异常类并将其添加到当前范围。如果在模块初始化函数中调用,则将其添加到模块中。

The following function creates a new Python exception class and adds it to the current scope. If it is called in a module initialization function, then it is added to the module.

第一个参数是新异常类的名称。第二个参数是新异常类的基类的类型对象;它默认为 Exception 的类型对象。返回值是新异常类的类型对象。

The first argument is the name of the new exception class. The second argument is the type object for the base class of the new exception class; it defaults to the type object for Exception. The return value is the type object for the new exception class.

PyObject* createExceptionClass(const char* name, PyObject* baseTypeObj = PyExc_Exception)
{
    using std::string;
    namespace bp = boost::python;

    string scopeName = bp::extract<string>(bp::scope().attr("__name__"));
    string qualifiedName0 = scopeName + "." + name;
    char* qualifiedName1 = const_cast<char*>(qualifiedName0.c_str());

    PyObject* typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0);
    if(!typeObj) bp::throw_error_already_set();
    bp::scope().attr(name) = bp::handle<>(bp::borrowed(typeObj));
    return typeObj;
}

使用函数如下:

调用模块初始化函数中的函数并将返回值存储在全局变量中:

Call the function in the module initialization function and store the return value in a global variable:

PyObject* myExceptionTypeObj = 0;

BOOST_PYTHON_MODULE(MyModule)
{
    ...
    myExceptionTypeObj = createExceptionClass("MyException");
    ...
}

提升 MyModule.MyException :

PyErr_SetString(myExceptionTypeObj, "Oh my!")

这篇关于Boost.Python自定义异常类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆