C API - Conversions from PyInt or PyFloat to a char *

Fredrik Lundh fredrik at pythonware.com
Wed Apr 19 12:57:46 EDT 2006


williams.jasonscott at gmail.com wrote:

> I'm looking at the C API and wanting to know a good way to convert
> Python numeric types to native c types.  For strings I've been using
> PyString_AsString(v) and thats great, but I would like to do the same
> for ints and floats.

    double d = PyFloat_AsDouble(v);
    long i = PyInt_AsLong(v);

    double real = PyComplex_RealAsDouble(v);
    double imag = PyComplex_ImagAsDouble(v);
    Py_complex c = PyComplex_AsCComplex(v);

    long i = PyLong_AsLong(v);
    unsigned long y = PyLong_AsUnsignedLong(v);
    double d = PyLong_AsDouble(v);
    PY_LONG_LONG l = PyLong_AsLongLong(v);
    // and others; see include/longobject.h for details

the float and int versions also available as "unsafe" macro versions

    double d = PyFloat_AS_DOUBLE(v);
    int i = PyInt_AS_LONG(op);

(the macro versions assume that that v points to a python object of the
right type; it's up to you to do the type check)

</F>






More information about the Python-list mailing list