[C++-sig] function as custom ctor

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Sun Nov 17 06:30:51 CET 2002


--- David Abrahams <dave at boost-consulting.com> wrote:
> "Achim Domma" <achim at procoders.net> writes:
> > I have a class which I don't want to change, with an ctor like this:
> >
> > class Blob {
> > public:
> > 	Blob(const char* data, const long length);
> > };
> >
> > From Python I want to pass the binary data in a string, so I want to use a
> > wrapper like
> >
> > Blob createBlob(const std::string data) {
> > 	return Blob(data.str(),data.size());
> > }
> >
> > Can I pass this funktion to boost.python in a way, that I could be used as
> > ctor? Something like this:
> >
> > class_<Blob>("Blob",init<>())
> >     .def( ??? , createBlob );
> >
> > and then from Python:
> >
> > data = "a string with data to be passed to the blob"
> > blob = Blob(data)
> 
> Not quite, but you can fake it:
> 
> First expose your class with no_init, then expose createBlob as
> "Blob".

Not quite? I think I am doing what Achim is looking for. It goes along the
lines of (untested!):

struct BlopPlus : Blob
{
  // Additional constructor(s) here
  BlopPlus(PyObject*, std::string const& s)
  : Blop(s.c_str(), s.size())
  {}

  // Don't forget the constructor that converts a Blob to a BlopPlus
  BlopPlus(PyObject*, Blop const& b)
  : Blop(b)
  {} 
};

class_<Blop, BlopPlus>("Blop", no_init)
  .def(init<std::string const&>())
  .def(init</* "normal" constructors, if any */>())
;

I believe this is re/mis-using the virtual function support, but it works great
for me.

Ralf


__________________________________________________
Do you Yahoo!?
Yahoo! Web Hosting - Let the expert host your site
http://webhosting.yahoo.com




More information about the Cplusplus-sig mailing list