Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when extending python with c, how do one cope with arbitrary size integers?

The Python/C API manual mentions conversion functions from⁽¹⁾ and to⁽²⁾ void pointers, which seem to be the only way to use arbitrary length python integers in C.
(1) : PyLong_FromVoidPtr() and format 0& with Py_BuildValue()
(2) : PyLong_AsVoidPtr() and formats 0, 0& and 0! with PyArg_…Parse…()

However, I haven't found⁽³⁾ in the manual, any indication about the way to use those void pointers to do whatever in C with those arbitrary long integers.
(3) : I tried a search for «voidptr», «void *» and «0&» but haven't thoroughly read it all yet.

Where can I find information about their inner structure or primitives to compute on them ?

like image 722
Camion Avatar asked May 03 '19 11:05

Camion


People also ask

How to take long integer in Python?

Type int(x) to convert x to a plain integer. Type long(x) to convert x to a long integer.

How big is Python integer?

These represent numbers in the range -2147483648 through 2147483647.

How does Python represent large integers?

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.


1 Answers

Actually, those functions are not to have "a pointer to an arbitrarily large integer", but literally just integer values as void * pointer, as in, casted to the type void *. See the implementations for PyLong_FromVoidPtr and PyLong_AsVoidPtr. It's there just to allow you to hold arbitrary pointers within Python, making sure the casting is done correctly.

As far as I can tell, the most practical way get arbitrary long integers from and into Python would be with int.to_bytes and int.from_bytes. There is actually a internal-ish API _PyLong_FromByteArray / _PyLong_AsByteArray for that which you can probably use. See the related question Python extension - construct and inspect large integers efficiently.

Note: Interestingly, there does not seem to be any C API, official or otherwise, to tell the bit or byte length of a Python integer value. In Python there is int.bit_length, but it does not appear to map to any publicly available function.

like image 194
jdehesa Avatar answered Sep 30 '22 04:09

jdehesa