[C++-sig] create a python object from scratch in boost.python?

Gary Oberbrunner garyo at genarts.com
Tue Jan 21 16:37:01 CET 2014


...
> 
> > > I think if you've exposed your c++ class, then there is a conversion
> > > from c++ object to python object. So
> > > bp::object plugin (Plugin_Info());
> 

> > Thanks -- I can indeed do that (or a proxy C++ class in any case).
> > I
> > was wondering though if it's possible to create an anonymous python
> > class in BP, without a "starter" C++ class as it were. But I
> > suppose that's mostly an academic question right now.

Well, it turns out I really do want to do this without a predefined C++ class, or something like that.

I want to have the C++ code be easily extensible, so I don't have to repeat myself too much when adding new attributes.  I tried making the proxy C++ class and exposing it, but it's very verbose and hard to maintain.

I switched to using a dict, and what I have now is almost there:

static bp::list EXTget_effects()
{
  bp::list effect_list;
  int n_effects = get_n_sapphire_effects();
  for (int i = 0; i < n_effects; i++) {
    Plugin_Info *pinfo = get_plugin_info_i(i);
    bp::dict ppinfo;
    ppinfo["name"] = (std::string)pinfo->plugin_name;
    ppinfo["category"] = (std::string)pinfo->category;
    ppinfo["n_effects"] = (int)pinfo->n_effects;
    ppinfo["n_inputs"] = (int)pinfo->n_inputs;
    ppinfo["custom_p"] = (int)pinfo->custom_p;
    effect_list.append(ppinfo);
  }
  return effect_list;
}

So now it returns a python list of python dicts.  All I want now is to override __getattr__ on each ppinfo dict so it returns the dict value as the attribute value, so in python I can reference effect_list[i].name instead of effect_list[i]['name'].  Or any alternative way to get the same effect.  Is that possible?

-- 
Gary Oberbrunner


More information about the Cplusplus-sig mailing list