0

i need to convert PyInt to C int. In my code

count=PyInt_FromSsize_t(PyList_Size(pValue))

pValue is a PyObject, PyList. the problem i was having is the PyList_Size is not returning me the correct list size (count is supposed to be 5, but it gave me 6 million), or there is a problem with data types since im in C code interfacing to python scripts. Ideally, i want count to be in a C int type.

i've found python/c APIs that return me long C data types... which is not what i want... anybody can point me to the correct method or APIs??

PeterG
  • 519
  • 2
  • 7
  • 15

1 Answers1

3

The PyInt_FromSsize_t() returns a full-fledged Python int object sitting in memory and returns its memory address — that is where the 6-million number is coming from. You just want to get the scalar returned by PyList_Size() and cast it to a C integer, I think:

count = (int) PyList_Size(pValue)

If the list could be very long you might want to think about making count a long instead, in which case you could cast to that specific type instead.

Note: a count of -1 means that Python encountered an exception while trying to measure the list length. Here are the docs you should read to know how to handle exceptions:

http://docs.python.org/c-api/intro.html#exceptions

Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147
  • i tried your suggestion, count was -1. But if i tried (int)PyInt_FromSsize_t(PyList_Size(pValue)) it also gave me the large number. So is it the PyList_Size screwing up? – PeterG Nov 24 '11 at 20:42
  • A count of `-1` means that your attempt to measure the length of what-you-thought-was-a-list has failed with a fatal Python exception. Most Python API calls can fail and return the integer `-1` or the pointer value `0` (NULL) to signal that they have failed. You should always check every call you make for such a value, and return the failure back into Python so that it can print the exception and a traceback for the user. – Brandon Rhodes Nov 24 '11 at 20:55