eddie_c
eddie_c

Reputation: 3421

How to specify return policy for object returned as part of a tuple in boost python

I have a function that creates a C++ object. Before the refactor, I was returning a pointer from the C++ function, and in the boost python wrapper declaration, I would use boost::python::return_value_policy<boost::python::manage_new_object>. Something like this:

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>()
);

Now I need to return more than just the object, but also some error messages, and the refactor basically changes the C++ function to let it return a tuple:

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

How should I specify the return policy with this change?

Upvotes: 0

Views: 728

Answers (1)

Matthew Scouten
Matthew Scouten

Reputation: 15571

I don't think that this is possible. What you probably need to do is change the function signature and re-wrap the function in python. Like this:

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

Then in python have a function like this:

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

Of course, what you should REALLY do is throw an exception. Boost::python does a very nice job of turning c++ exceptions in to python exception and vice-versa

Upvotes: 1

Related Questions