exposing boost::tuple part of class to boost python
I've been trying to figure out how to expose a property in my class that is a boost::tuple. The tuple is defined as follows:
typedef boost::shared_ptr<Action> action_ptr;
typedef boost::tuple<BattleCharacter*, action_ptr > ActionTargetTuple;
It's contained with a class defined as follows:
class Action : public Cloneable<Action>
{
public:
//Irrelevant Code Omitted
std::vector<ActionTargetTuple> Targets;
}
I've seen numerous articles while I was searching about how to convert a boost::tuple into a python tuple, but that's not what I'm looking to do. I want to be able to access the tuple as it exists on the Action class. (I know how to do the vector part).
class_<Action, std::auto_ptr<ActionWrapper> >("Action")
.def("Targets", &Action::Targets)
;
I expose it simply as above. I figured I might be able to expose it by some variation on the below:
class_<ActionTargetTuple>("ActionTargetTuple")
.def("get", &开发者_高级运维amp;ActionTargetTuple::get<int>, return_value_policy<reference_existing_object>())
;
then use get from python, but if it is doable in this way, I'm not sure what the set up needs to be. Does anyone know how to do this/could suggest an alternative?
Thanks
You can use:
...
.add_property("Targets", & ActionTargetTuple::get, &ActionTargetTuple::set)
to make a read-write property using getter/setter methods in c++
If you want to control ownership:
namespace bp = boost::python;
...
.add_property("Targets",
bp::make_function(&ActionTargetTuple::get, bp::return_value_policy<...>()),
bp::make_function(&ActionTargetTuple::set, bp::return_value_policy<...>())
)
Besides using add_property
as explained in the previous answer, and writing accessor functions, you can consider writing converters for your tuple (between boost::tuple
and boost::python::tuple
) and exposing those attributes directly with def_readonly
or def_readwrite
. It is worth it if you have many such attributes to expose.
This has a template you adapt can for c++→python conversion (use boost::tuple instead of std::pair), though unless you go c++0x, you have to write out templates for different number of arguments.
If your property is read-write, additionaly define from-python converter, you find examples on the web. Here is my code I use to define generic sequence-std::vector converter. In your case, you have to check that the python object is a sequence, that it has the right number of items, that you can extract required types from each of them; and then return new boost::tuple object.
HTH, edx.
P.S. I found ackward has the converters ready, perhaps you could just reuse it. Doc here
精彩评论