Change bytestring to use type wrapper py::bytes<std::string>

py::bytes<T> will work with any T which has these methods
const char* data() and int size()

Other types can be accommodated by specializing bytes<T>
and type_caster<bytes<T>>
This commit is contained in:
Valery Yundin 2015-12-30 12:26:08 +01:00
parent f2c5e8f6a2
commit 2362cc128e
2 changed files with 11 additions and 10 deletions

View File

@ -378,15 +378,15 @@ public:
#endif
};
template <> class type_caster<bytestring> : public type_caster<std::string> {
template <typename T> class type_caster<bytes<T>> : public type_caster<T> {
public:
static PyObject *cast(const bytestring &src, return_value_policy /* policy */, PyObject * /* parent */) {
return PYBIND11_FROM_STRING_AND_SIZE(src.c_str(), src.size());
static PyObject *cast(const bytes<T> &src, return_value_policy /* policy */, PyObject * /* parent */) {
return PYBIND11_FROM_STRING_AND_SIZE(src.data(), src.size());
}
#if PY_MAJOR_VERSION >= 3
PYBIND11_TYPE_CASTER(bytestring, "bytes");
PYBIND11_TYPE_CASTER(bytes<T>, "bytes");
#else
PYBIND11_TYPE_CASTER(bytestring, "str");
PYBIND11_TYPE_CASTER(bytes<T>, "str");
#endif
};

View File

@ -259,13 +259,14 @@ inline iterator handle::end() { return iterator(nullptr); }
PYBIND11_OBJECT(Name, Parent, CheckFun) \
Name() : Parent() { }
class bytestring : public std::string {
template <typename T>
class bytes : public T {
public:
using std::string::string;
using T::T;
bytestring(const std::string& src) : std::string(src) { }
bytestring(std::string&& src) : std::string(std::move(src)) { }
bytestring() : std::string() { }
bytes(const T& src) : T(src) { }
bytes(T&& src) : T(std::move(src)) { }
bytes() : T() { }
};
class str : public object {