[C++-sig] Auto-converting to a custom string type?

Aaron Bentley abentley at panoramicfeedback.com
Mon Jul 18 18:56:00 CEST 2005

Aaron Bentley wrote:
> Our library uses a custom unicode string type called 'StringBuffer'.
> I'd like to be able to auto-convert python unicode objects into
> StringBuffers, because the alternative (AFAICT) it to wrap every
> function that takes a StringBuffer parameter.

Not solved yet, but progress:
I found Ralf Grosse-Kunstleve's approach, and I got it to work

class StringBufferPy: public StringBuffer
   StringBufferPy(PyObject *mine, PyObject *uni_str)
      string utf8str = call_method<string>(uni_str, "encode", "UTF-8");
      pythonhelp::appendUTF8(*this, utf8str);
   StringBufferPy(PyObject *mine, StringBuffer const &sb)

And then
   ///Wrap the StringBuffer class
   class_<StringBuffer, StringBufferPy>("StringBuffer", no_init)
      .def(init<StringBuffer const &>())
      .def(init<const char *>())
      .def(init<PyObject *>())


So now the problem is that if I construct a StringBuffer from a
StringBuffer, it tries (and fails) to invoke StringBuffer.encode.  I
don't really want to support StringBuffer.encode, since repeated
encodes/decodes are pretty inefficient....

Aaron Bentley
Director of Technology
Panometrics, Inc.

More information about the Cplusplus-sig mailing list