سؤال

I am using the Python/C API and would like a C function to take a Python long integer argument, nPyLong, and convert it to a char array, nString, in base 10. Here is a snippet of what I would like to do.

PyObject *nPyLong;
PyArg_ParseTuple(args, "O", nPyLong);

PyLong_Check(nPyLong) // returns true

const char *nString;
// This function doesn't exist but demonstrates the functionality
PyLong_AsCharArray(&nString, nPyLong, 10);

The API reference mentions a function PyObject* PyLong_FromString(char *str, char **pend, int base) which converts a C char array to a Python long integer, given an arbitrary base, but I cannot find a function which does the inverse.

Is this possible? One idea is to convert the Python long integer to a Python string object and then convert to a C char array, but there are no string functions to handle long ints either. It seems the only way for C to handle Python long ints is to convert to C int types, all of which would overflow in my application.

هل كانت مفيدة؟

المحلول

Use PyObject_Str() (or PyObject_Bytes()) and convert the resultant object into a char*.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top