Writing an Extension: 2 questions (so far)

Martin von Loewis loewis at informatik.hu-berlin.de
Thu Jan 3 13:14:19 EST 2002


"Tyler W. Wilson" <tyler.w.wilson at gte.net> writes:

> 2) I am writing one function which takes a string, either multibyte or
> Unicode. I want to call PyArg_ParseTuple once, and have it convert the
> string passed into my desired output (n this case, Unicode). Some thing
> like: ParseTuple(args, "u", &ustr); But it appears that the interpreter will
> not automatically do this for, or is there a way?

No. If a multibyte string is passed, you expect a conversion to a
Py_UNICODE*. Somebody needs to allocate the memory, and you would need
to release it afterwards. However, you don't need release anything if
you are passed a Unicode object. So the API you are proposing cannot
work.

Instead, I recommend to use O&, and a conversion function. This
conversion function should always convert to a PyObject* representing
a Unicode object, by:
- INCREFing the argument if it is a Unicode object, or
- invoking PyUnicode_FromEncodedObject if it is a MBCS string.
Then, your application would get a PyUnicodeObject*, which it would
need to DECREF.

Regards,
Martin




More information about the Python-list mailing list