What's the reverse of Py_BuildValue("u#" ?

"Martin v. Löwis" martin at v.loewis.de
Wed Jan 24 02:35:42 EST 2007


sndive at gmail.com schrieb:
> How could I get the pointer to and the length of ucs2 array out of a 
> PyObject representing a string? Something that works whether PyObject
> string is in unicode or not.

You can use PyObject_Unicode(o) to convert the object to Unicode first,
then use PyUnicode_AsUnicode to convert it to a Py_UNICODE array, and
PyUnicode_GetSize to find out what the length is. Notice that this will
be UCS-2 only if Py_UNICODE is 16 bits on your platform. If you really
want UCS-2 always, you need to convert the string again using
PyUnicode_AsEncodedObject, then PyString_AsString to find out what
the UCS-2 bytes are.

Remember to check for errors for all these functions, and remember
to decref the results when you don't need them any longer.

> 
> Also could I replace a sequence
> 
>    if(PyBool_Check(obj)) {
>...
>    }
>    if(PyString_Check(obj)) { // would this be true for any string
>type?
>...
>    }
>    if(PyFloat_Check(obj)) {
>...
> with a switch?

Not easily. Also, PyString_Check is true only for the byte string
type (and its subtypes).

Regards,
Martin



More information about the Python-list mailing list