why there's no PyLong_AsString() ?

Alex Martelli aleax at aleax.it
Wed Sep 19 08:26:39 EDT 2001


"Silvio Arcangeli" <sarcangeli at montrouge.sema.slb.com> wrote in message
news:mailman.1000899325.27302.python-list at python.org...
> Hello,
> I am dealing with Python long objects in my extension module (I use them
to
> store a 64 bits non-standard integer type).
> To convert the C type into a Python long I just pass through a string
using
> itoa()-like function and the PyLong_FromString(),
> but when I have to get back the object from Python I have no way to
> retrieve (in C) a string from it (so that I can then retrieve my variable
> with the atoi()-like function). Why is this function missing in the API?

Starting with any PyObject* o, whether it refers to a Python long
or any other stringifiable Python object:

    PyObject* as_str = PyObject_Str(o);
    if(!as_str) { /* error-handling to choice */ }
    const char* the_c_str = PyString_AsString(as_str);
    /* now use the_c_str as you wish, and when done: */
    Py_DECREF(as_str);

It wouldn't be right to package this up as an API function because
of memory-ownership issues -- who should own (be responsible for
freeing) the returned C-ish "string"?  Using strdup (and making
the caller responsible for freeing the resulting char*) might be
a substantial overhead, a caller-passed buffer would lead to
buffer-overflow issues, etc, etc.

With just 3 utterly simple API calls (including the decref as
a "call":-) this idiom is hardly difficult to merge with your
own C code, after all, is it?-)


Alex






More information about the Python-list mailing list