diff options
author | Hugo Lima <hugo.lima@openbossa.org> | 2010-01-20 15:50:10 -0200 |
---|---|---|
committer | Hugo Lima <hugo.lima@openbossa.org> | 2010-01-20 16:03:50 -0200 |
commit | cd12b72f152f970a86cac12f62a0f9d1edd3f6d8 (patch) | |
tree | 5ac48e13c445c5510e0e3f8bbcd7b4e078ee30f1 /libshiboken | |
parent | 9ac13a27e49439ffcef2291da01ee4c8b6b930d0 (diff) |
Add special conversion rules to the char type.
A type is convertible to char if it is a number or a 1-sized char.
Reviewed by Marcelo Lira <marcelo.lira@openbossa.org>
Diffstat (limited to 'libshiboken')
-rw-r--r-- | libshiboken/conversions.h | 31 |
1 files changed, 28 insertions, 3 deletions
diff --git a/libshiboken/conversions.h b/libshiboken/conversions.h index 52ac75848..5ad5fec74 100644 --- a/libshiboken/conversions.h +++ b/libshiboken/conversions.h @@ -236,9 +236,34 @@ struct Converter_PyInt } }; -template <> struct Converter<char> : Converter_PyInt<char> {}; -template <> struct Converter<signed char> : Converter_PyInt<signed char> {}; -template <> struct Converter<unsigned char> : Converter_PyInt<unsigned char> {}; +/// Check if we can treat the pyobj as a char, i.e. it's a number or a string with just one character. +#define SbkChar_Check(pyobj) (PyNumber_Check(pyobj) || (PyString_Check(pyobj) && PyString_Size(pyobj) == 1)) + +/// Specialization to convert char and unsigned char, it accepts Python numbers and strings with just one character. +template <typename CharType> +struct CharConverter +{ + static inline bool isConvertible(PyObject* pyobj) { return SbkChar_Check(pyobj); } + static inline PyObject* toPython(void* cppobj) { return toPython(*reinterpret_cast<CharType*>(cppobj)); } + static inline PyObject* toPython(const CharType& cppobj) { return PyInt_FromLong(cppobj); } + static CharType toCpp(PyObject* pyobj) + { + long result; + if (PyString_Check(pyobj)) { + assert(PyString_Size(pyobj) == 1); // This check is made on SbkChar_Check + result = PyString_AS_STRING(pyobj)[0]; + } else { + result = PyLong_AsLong(pyobj); + if (overflowCheck<long, CharType>(result)) + PyErr_SetObject(PyExc_OverflowError, 0); + } + return static_cast<CharType>(result); + } +}; + +template <> struct Converter<char> : CharConverter<char> {}; +template <> struct Converter<signed char> : CharConverter<signed char> {}; +template <> struct Converter<unsigned char> : CharConverter<unsigned char> {}; template <> struct Converter<int> : Converter_PyInt<int> {}; template <> struct Converter<unsigned int> : Converter_PyInt<unsigned int> {}; template <> struct Converter<short> : Converter_PyInt<short> {}; |