diff options
author | Lauro Neto <lauro.neto@openbossa.org> | 2010-02-18 17:53:53 -0300 |
---|---|---|
committer | Lauro Neto <lauro.neto@openbossa.org> | 2010-02-19 12:59:34 -0300 |
commit | 4b0fa3fd45ed42cf881a25897ed66b5c0cf3a3fa (patch) | |
tree | 5a5ee9e41f223cdc4cba13ec864972d64067a117 | |
parent | f425ded9520c965202b62b1c2d172608f803497b (diff) |
Adding sequenceToIntArray helper function
-rw-r--r-- | libshiboken/helper.cpp | 37 | ||||
-rw-r--r-- | libshiboken/helper.h | 8 |
2 files changed, 45 insertions, 0 deletions
diff --git a/libshiboken/helper.cpp b/libshiboken/helper.cpp index 4523a2059..3346484e4 100644 --- a/libshiboken/helper.cpp +++ b/libshiboken/helper.cpp @@ -69,4 +69,41 @@ PySequenceToArgcArgv(PyObject* argList, int* argc, char*** argv, const char* def return true; } +int* +sequenceToIntArray(PyObject* obj, bool zeroTerminated) +{ + int* array = NULL; + int i; + int size; + + if (!PySequence_Check(obj)) { + PyErr_SetString(PyExc_TypeError, "Sequence of ints expected"); + return NULL; + } + + size = PySequence_Size(obj); + + array = new int[size + zeroTerminated ? 1 : 0]; + + for (i = 0; i < size; i++) { + PyObject* item = PySequence_GetItem(obj, i); + if (!PyInt_Check(item)) { + PyErr_SetString(PyExc_TypeError, "Sequence of ints expected"); + Py_DECREF(item); + if (array) + delete array; + return NULL; + } else { + array[i] = PyInt_AsLong(item); + Py_DECREF(item); + } + } + + if (zeroTerminated) + array[i] = 0; + + return array; +} + + } // namespace Shiboken diff --git a/libshiboken/helper.h b/libshiboken/helper.h index 84084fef2..3bda34a7b 100644 --- a/libshiboken/helper.h +++ b/libshiboken/helper.h @@ -85,6 +85,14 @@ inline PyObject* makeTuple(const A& a, const B& b, const C& c, const D& d, const */ LIBSHIBOKEN_API bool PySequenceToArgcArgv(PyObject* argList, int* argc, char*** argv, const char* defaultAppName = 0); +/** + * Convert a python sequence into a heap-allocated array of ints. + * + * \returns The newly allocated array or NULL in case of error or empty sequence. Check with PyErr_Occurred + * if it was successfull. + */ +LIBSHIBOKEN_API int* sequenceToIntArray(PyObject* obj, bool zeroTerminated = false); + } // namespace Shiboken #endif // HELPER_H |