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

  • Thread starter williams.jasonscott
  • Start date
W

williams.jasonscott

Hi,

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. I have found PyFloat_AsString in the source but
it seems to be undocumented and some of the comments make me think that
I shouldn't use it but I've given it a go anyhow. It is defined in
floatobject.h as:

PyAPI_FUNC(void) PyFloat_AsString(char*, PyFloatObject *v);

and also:

PyAPI_FUNC(void) PyFloat_AsReprString(char*, PyFloatObject *v);

And I have a few questions:

Should I use these calls? And the comment that I am concerned about
from floatobject.c is:

315 /* XXX PyFloat_AsString and PyFloat_AsReprString should be
deprecated:
316 XXX they pass a char buffer without passing a length.
317 */

OK so what the caller can manage the buf len, but is there something
else I should be concerned about?

If these types of calls are the way to go, is there a call for int?
And how should I convert a PyObject to a PyFloatObject?

If this isn't a good approach, what is?

thanks,

~jason
 
F

Fredrik Lundh

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>
 
W

williams.jasonscott

Thanks for the reply, This is the approach I have taken. Convert to a
c numeric and take it from there.

Is there movment to add functions like PyInt_AsString ? I noticed it
mentioned in response to a PEP...

thanks,
~jason
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,508
Members
48,193
Latest member
DannyRober

Latest Threads

Top