Skip to content

Commit 3237080

Browse files
committed
Matching Python 2 int behavior on Python 2
1 parent 0a0758c commit 3237080

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

include/pybind11/cast.h

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -980,11 +980,19 @@ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_t
980980
static handle cast(T src, return_value_policy /* policy */, handle /* parent */) {
981981
if (std::is_floating_point<T>::value) {
982982
return PyFloat_FromDouble((double) src);
983-
} else if (sizeof(T) <= sizeof(long)) {
983+
} else if (sizeof(T) <= sizeof(ssize_t)) {
984+
#if PY_VERSION_HEX < 0x03000000
985+
// This returns a long automatically if needed
984986
if (std::is_signed<T>::value)
985-
return PyLong_FromLong((long) src);
987+
return PyInt_FromSsize_t((ssize_t) src);
986988
else
987-
return PyLong_FromUnsignedLong((unsigned long) src);
989+
return PyInt_FromSize_t((size_t) src);
990+
#else
991+
if (std::is_signed<T>::value)
992+
return PyLong_FromSsize_t((ssize_t) src);
993+
else
994+
return PyLong_FromSize_t((size_t) src);
995+
#endif
988996
} else {
989997
if (std::is_signed<T>::value)
990998
return PyLong_FromLongLong((long long) src);

tests/test_builtin_casters.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,4 +155,9 @@ TEST_SUBMODULE(builtin_casters, m) {
155155
// test_complex
156156
m.def("complex_cast", [](float x) { return "{}"_s.format(x); });
157157
m.def("complex_cast", [](std::complex<float> x) { return "({}, {})"_s.format(x.real(), x.imag()); });
158+
159+
// test int vs. long (Python 2)
160+
m.def("int_cast", [](){return (int) 42;});
161+
m.def("long_cast", [](){return (long) 42;});
162+
m.def("longlong_cast", [](){return (long long) 42;});
158163
}

tests/test_builtin_casters.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,3 +323,9 @@ def test_numpy_bool():
323323
assert convert(np.bool_(False)) is False
324324
assert noconvert(np.bool_(True)) is True
325325
assert noconvert(np.bool_(False)) is False
326+
327+
def test_int_long():
328+
import sys
329+
type(m.int_cast()) == type(1)
330+
type(m.long_cast()) == type(1)
331+
type(m.longlong_cast()) == type(sys.maxint + 1)

0 commit comments

Comments
 (0)