On 8 Aug 2021, at 18:53, Serhiy Storchaka <storchaka@gmail.com> wrote:
08.08.21 07:08, Stephen J. Turnbull пише:
Serhiy Storchaka writes:
Python integers have arbitrary precision. For serialization and interpolation with other programs and libraries we need to represent them [...]. [In the case of non-standard precisions,] [t]here are private C API functions _PyLong_AsByteArray and _PyLong_FromByteArray, but they are for internal use only.
I am planning to add public analogs of these private functions, but more powerful and convenient.
PyObject *PyLong_FromBytes(const void *buf, Py_ssize_t size, int byteorder, int signed)
Py_ssize_t PyLong_AsBytes(PyObject *o, void *buf, Py_ssize_t n, int byteorder, int signed, int *overflow)
I don't understand why such a complex API is useful as a public facility.
There are several goals:
1. Support conversion to/from all C integer types (char, short, int, long, long long, intN_t, intptr_t, intmax_t, wchar_t, wint_t and corresponding unsigned types), POSIX integer types (pid_t, uid_t, off_t, etc) and other platfrom or library specific integer types (like Tcl_WideInt in libtcl). Currently only supported types are long, unsigned long, long long, unsigned long, ssize_t and size_t. For other types you should choose the most appropriate supertype (long or long long, sometimes providing several varians) and manually handle overflow.
There are requests for PyLong_AsShort(), PyLong_AsInt32(), PyLong_AsMaxInt(), etc. It is better to provide a single universal function than extend API by several dozens functions.
But how would you convert from the buffer to the actual type you want? IMHO “pid_t a_pid; Py_LongAsBytes(val, &a_pid, sizeof(pid_t), …)” would be worse than having a number of aliases. The API is more cumbersome to use, and you loose type checking from the C compiler. Other than that, the variants you mention could in general just by aliases for conversion functions to/from the basic C types. Ronald — Twitter / micro.blog: @ronaldoussoren Blog: https://blog.ronaldoussoren.net/