c++ - 如何为在boost python中作为元组的一部分返回的对象指定返回策略

标签 c++ boost boost-python

我有一个创建 C++ 对象的函数。在重构之前,我从 C++ 函数返回一个指针,在 boost python 包装器 声明 中,我将使用 boost::python::return_value_policy<boost::python::manage_new_object> .像这样:

MyObject* create_object_from_description(std::string& description) 
{
    ...
    return myObject;
}
BOOST_PYTHON_MODULE(pymol) {
    boost::python::def("create_obj_from_desc", create_object_from_description,
        (boost::python::arg("description")),
        "",
        boost::python::return_value_policy<boost::python::manage_new_object>()
);

现在我不仅需要返回对象,还需要返回一些错误消息,重构基本上更改了 C++ 函数,让它返回一个元组:

boost::python::tuple create_object_from_description(std::string& description) 
{
    ...
    return boost::python::make_tuple(myObject, errmsg);
}

我应该如何指定此更改的返回政策?

最佳答案

我认为这是不可能的。您可能需要做的是更改函数签名并在 python 中重新包装函数。像这样:

boost::python::tuple create_object_from_description(std::string& description, 
                                                    MyObject& myObject) 
{
    myObject = mo; 
    return errmsg 
}

然后在python中有这样一个函数:

def create_object_from_description(description):
    mo = MyObject()
    errmsg = pymol.create_object_from_description(description, mo)
    return mo, errmsg

当然,您真正应该做的是抛出异常。 Boost::python 在将 C++ 异常转换为 Python 异常方面做得非常好,反之亦然

关于c++ - 如何为在boost python中作为元组的一部分返回的对象指定返回策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4855555/

相关文章:

python - 为使用 Opencv 2.3 的 c++ 类 boost Python 包装器

python - 在 C++ 中运行 python

c++ - 如何将字符串数组从 VBScript 传递到 COM+

c++ - boost::log-在库/插件中使用独立的严重级别

c++ - 使用 boost.python 将类暴露给 python 时出现构建错误

c++ - boost::posix_time::time_duration::total_seconds 有什么问题?

c++ - 正则表达式:查找所有子表达式(使用 boost::regex)

c++ - Boost Test 寄存器异常翻译器

c++ - 如何阻止 GNU GCC 修改 dll 导入函数名称

c++ - 我的程序出现 abort() 错误,但由于它是程序的加载部分,我无法调试它?