[Python-Dev] Convert Py_Buffer to Py_UNICODE

M.-A. Lemburg mal at egenix.com
Mon May 2 21:12:27 CEST 2011


Sijin Joseph wrote:
> Hi - I am working on a patch where I have an argument that can either be a
> unicode string or binary data, I parse the argument using the
> PyArg_ParseTuple method using the s* format specification and get a
> Py_Buffer.
> 
> I now need to convert this Py_Buffer object to a Py_Unicode and pass it into
> a function. What is the best way to do this? If I determine that the passed
> argument was binary using another flag parameter then I am passing
> Py_Buffer->buf as a pointer to the start of the data.

I don't understand why you'd want to convert PyUnicode to PyBytes
(encoded as UTF-8), only to decode it again afterwards in order
to pass it to some other PyUnicode API.

It'd be more efficient to use the "O" parser marker and then
use PyObject_GetBuffer() to convert non-PyUnicode objects to
a Py_buffer.

> This is in winsound module, here's the relevant code snippet
> 
> sound_playsound(PyObject *s, PyObject *args)
> {
>     Py_buffer *buffer;
>     int flags;
>     int ok;
>     LPCWSTR pszSound;
> 
>     if (PyArg_ParseTuple(args, "s*i:PlaySound", &buffer, &flags)) {
>         if (flags & SND_ASYNC && flags & SND_MEMORY) {
>             /* Sidestep reference counting headache; unfortunately this also
>                prevent SND_LOOP from memory. */
>             PyBuffer_Release(buffer);
>             PyErr_SetString(PyExc_RuntimeError, "Cannot play asynchronously
> from memory");
>             return NULL;
>         }
> 
>         if(flags & SND_MEMORY) {
>             pszSound = buffer->buf;
>         }
>         else {
>             /* pszSound = ????; */
>         }
> 
> -- Sijin
> 
> 
> 
> 
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/mal%40egenix.com

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 02 2011)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________
2011-06-20: EuroPython 2011, Florence, Italy               49 days to go

::: Try our new mxODBC.Connect Python Database Interface for free ! ::::


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/


More information about the Python-Dev mailing list