Panda3D
py_compat.cxx
Go to the documentation of this file.
1 /**
2  * @file py_compat.cxx
3  * @author rdb
4  * @date 2017-12-03
5  */
6 
7 #include "py_compat.h"
8 #include "py_panda.h"
9 
10 #ifdef HAVE_PYTHON
11 
12 #if PY_MAJOR_VERSION < 3
13 /**
14  * Given a long or int, returns a size_t, or raises an OverflowError if it is
15  * out of range.
16  */
17 size_t PyLongOrInt_AsSize_t(PyObject *vv) {
18  if (PyInt_Check(vv)) {
19  long value = PyInt_AS_LONG(vv);
20  if (value < 0) {
21  PyErr_SetString(PyExc_OverflowError,
22  "can't convert negative value to size_t");
23  return (size_t)-1;
24  }
25  return (size_t)value;
26  }
27 
28  if (!PyLong_Check(vv)) {
29  Dtool_Raise_TypeError("a long or int was expected");
30  return (size_t)-1;
31  }
32 
33  size_t bytes;
34  int one = 1;
35  int res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
36  SIZEOF_SIZE_T, (int)*(unsigned char*)&one, 0);
37 
38  if (res < 0) {
39  return (size_t)res;
40  } else {
41  return bytes;
42  }
43 }
44 #endif
45 
46 #endif // HAVE_PYTHON