[C++-sig] Re: const char arrays
David Abrahams
dave at boost-consulting.com
Wed Aug 6 13:43:20 CEST 2003
"Ralf W. Grosse-Kunstleve" <rwgk at yahoo.com> writes:
> --- Niall Douglas <s_sourceforge at nedprod.com> wrote:
>> struct custom_string_to_python_str
>> {
>> static PyObject* convert(custom_string const& s)
>> {
>> return
>> boost::python::incref(boost::python::object(s.value()).ptr());
>> }
>> };
>>
>> Isn't this making use of boost.python's inbuilt std::string
>> converter? ie; it's not converting to a python string itself.
>
> Yes. Just to keep the example simple. Or maybe because I was too lazy to figure
> out the raw C API call.
Err, no. Trace it in a debugger; the conversion should not go through
std::string at all. If it does I'm very surprised.
>> For some non-std::string based string, would it be more like:
>>
>> struct custom_string_to_python_str
>> {
>> static PyObject* convert(custom_string const& s)
>> {
>> return
>> boost::python::incref(PyString_FromStringAndSize(s.text(),
>> s.length()));
>> }
>> };
>
> Close, but I think you are leaking a reference count. This should do the job:
>
> return PyString_FromStringAndSize(s.text(), s.length());
>
> The bottom line is that you have to return a new Python reference.
> How exactly you do this is entirely up to you.
On the other hand, Ralf's instincts were good; it's generally better
to use high-level Boost.Python calls than low-level Python 'C' API
calls. When the converter mechanism is ready for us to document, it
will probably not be returning raw PyObject*s.
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list