[C++-sig] Re: returning auto_ptr, `No to_python converter' ?

David Abrahams dave at boost-consulting.com
Wed Jun 18 21:42:11 CEST 2003


"Jacques A. Vidrine" <nectar-pycpp at celabo.org> writes:

> Hi All!
> Does this ring any bells?
>
>   #include <memory>
>   #include <string>
>   #include <boost/python.hpp>   // Boost 1.30.0
>
>   std::auto_ptr<std::string> example() {
> 	return std::auto_ptr<std::string>(new std::string("hello"));
>   }
>
>   using namespace boost::python;
>   BOOST_PYTHON_MODULE(example) {
> 	def("example", example);
>   }
>
>   >>> import example
>   >>> example.example()
>   Traceback (most recent call last):
>     File "<stdin>", line 1, in ?
>   TypeError: No to_python (by-value) converter found for C++ type: St8auto_ptrISsE
>
> Seems I'm missing something, but I can't quite put my finger on it :-)
> Cheers,

See my reply to Jarda Gresula (just posted)...

That will help you understand things, but it won't solve your problem.
My recommendations for Jarda cause auto_ptr<T> to be converted to a
Python T object which refers to its C++ object through a copy of the
auto_ptr object.

std::string is converted to Python as a regular Python string, and
there's no way to get a Python string to use an auto_ptr to hold its
storage.  I think you just want to register a custom to-python
converter for std::auto_ptr<std::string>.  Something like:

    struct auto_ptr_string_to_python
        : to_python_converter<simple, auto_ptr_string_to_python>
    {
        static PyObject* convert(std::auto_ptr<std::string> const& x)
        {
            return PyString_FromStringAndSize(x->c_str(), x->size());
        }
    };

Just constructing one of those in your module initialization function
should handle it.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list