You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Boost 1.88.0,如何使用boost::python将自定义C++ std::exception导出到Python?

基于Boost 1.88.0,如何使用boost::python将自定义C++ std::exception导出到Python?

嘿,我之前在基于Boost 1.88.0做C++与Python的交互开发时,正好碰到了要把自定义std::exception导出到Python的需求,查了不少相关讨论后,整理出了一套可行的实现方案,分享给你:

第一步:定义规范的C++自定义异常类

首先要确保你的异常类正确继承std::exception,并重写what()方法(这是std::exception的核心虚函数,用于返回错误信息),同时可以根据需求添加自定义字段比如错误码:

#include <stdexcept>
#include <string>

class cException : public std::exception {
private:
    const std::string m_message;
    const int m_code;
public:
    // 构造函数,初始化错误消息和可选错误码
    cException(const std::string &message, const int &code = -1)
        : m_message(message), m_code(code) {}

    // 析构函数,兼容C++旧标准的throw()声明
    virtual ~cException() throw() {}

    // 重写std::exception的what()方法,返回错误消息
    virtual const char* what() const throw() {
        return m_message.c_str();
    }

    // 获取自定义错误码的成员方法
    int get_code() const throw() {
        return m_code;
    }
};

第二步:用boost::python完成异常导出与关联

接下来要通过boost::python把C异常和Python异常类型绑定,核心是注册异常翻译器,让C抛出的异常能自动转换成Python可捕获的异常类型:

#include <boost/python.hpp>
#include <boost/python/exception_translator.hpp>

using namespace boost::python;

// 定义异常翻译器:将cException转换为Python可识别的异常
void translate_cException(const cException& e) {
    // 先关联C++异常类到Python的自定义异常类型
    object exc_type = class_<cException, bases<std::exception>>("cException")
        .def(init<const std::string&, optional<int>>())
        .def("what", &cException::what)
        .def("get_code", &cException::get_code)
        .ptr();

    // 设置Python的异常信息,让Python端能捕获到具体错误
    PyErr_SetString(exc_type.ptr(), e.what());
}

// 导出Python模块
BOOST_PYTHON_MODULE(your_custom_module) {
    // 注册异常翻译器
    register_exception_translator<cException>(&translate_cException);

    // 直接注册异常类,让Python也能主动实例化该异常
    class_<cException, bases<std::exception>>("cException", init<const std::string&, optional<int>>())
        .def("what", &cException::what)
        .def("get_code", &cException::get_code);
}

关键注意点

  • 一定要重写what()方法:这是std::exception的强制要求,也是Python端获取错误信息的关键入口
  • 异常翻译器是核心:它负责在C++异常抛出时,自动转换成Python能处理的异常类型,保证跨语言的异常传递通顺
  • 关联继承关系:注册异常类时指定bases<std::exception>,能让Python端的异常层级和C++保持一致,更符合Python的异常处理习惯

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 13:43:14