Skip to content

Add PyLong_FromInt64() and PyLong_AsInt64() #32

@vstinner

Description

@vstinner

Add 8 new functions to the limited C API to convert C <stdint.h> numbers from/to Python int:

// Return a Python int on success.
// Set an exception and return NULL on error.
PyAPI_FUNC(PyObject*) PyLong_FromInt32(int32_t value);
PyAPI_FUNC(PyObject*) PyLong_FromUInt32(uint32_t value);
PyAPI_FUNC(PyObject*) PyLong_FromInt64(int64_t value);
PyAPI_FUNC(PyObject*) PyLong_FromUInt64(uint64_t value);

// Set *value and return 0 on success.
// Set an exception and return -1 on error.
PyAPI_FUNC(int) PyLong_AsInt32(PyObject *obj, int32_t *value);
PyAPI_FUNC(int) PyLong_AsUInt32(PyObject *obj, uint32_t *value);
PyAPI_FUNC(int) PyLong_AsInt64(PyObject *obj, int64_t *value);
PyAPI_FUNC(int) PyLong_AsUInt64(PyObject *obj, uint64_t *value);

UPDATE 1: I removed PyLong_FromInt32() and PyLong_FromUInt32() functions.

UPDATE 2: I renamed To functions to As functions.

UPDATE 3: I added back PyLong_FromInt32() and PyLong_FromUInt32() functions for 32-bit systems.

  • As functions call obj.__index__() if obj is not a Python int.
  • As functions converting to unsigned integer raises ValueError if value is negative
  • As functions raise OverflowError if the value is too big (doesn't fit into the C integer range)

Compared to PyLong_AsLong(), As function return value is status (success or error, 0 or -1) and the result is set in the value argument (on success). It avoids having to call PyErr_Occurred() to distinguish -1 (success) and -1 (error). See Problem #1 for details.

Links:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions