1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, this is much easier than I thought it would be. And it doesn't even return the suffix 'L'!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.