38 template <>
struct type_caster<
Util::String>
41 bool from_python(handle src, uint8_t flags, cleanup_list* )
noexcept
43 handle load_src = src;
48 else if (!PyUnicode_Check(load_src.ptr()))
50 return load_bytes(load_src);
52 object utfNbytes = steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
"utf-8",
nullptr));
59 const char *buffer =
reinterpret_cast<const char *
>(PyBytes_AsString(utfNbytes.ptr()));
60 size_t length = (size_t)PyBytes_Size(utfNbytes.ptr());
61 value.Set(buffer, length);
66 const char *buffer = src.AsCharPtr();
67 size_t nbytes = size_t(src.Length());
68 handle s = PyUnicode_DecodeUTF8(buffer, nbytes,
nullptr);
76 if (PyBytes_Check(src.ptr()))
80 const char *bytes = PyBytes_AsString(src.ptr());
83 value.Set(bytes, (
size_t)PyBytes_Size(src.ptr()));
93 template <>
class type_caster<
Util::Variant>
95 template <
typename T>
using Caster = make_caster<detail::intrinsic_t<T>>;
98 bool try_load(handle src, uint8_t flags, cleanup_list* cleanup)
101 if (!caster.from_python(src, flags, cleanup))
106 if constexpr (is_pointer_v<T>)
108 static_assert(Caster<T>::IsClass,
109 "Binding 'Variant<T*,...>' requires that 'T' can also be bound by nanobind.");
110 value = caster.operator cast_t<T>();
112 else if constexpr (Caster<T>::IsClass)
117 value = caster.operator cast_t<T&>();
121 value = std::move(caster).operator cast_t<T&&>();
126 bool from_python(handle src, uint8_t flags, cleanup_list* cleanup)
noexcept {
129 try_load<int>(src, flags, cleanup),
130 try_load<uint>(src, flags, cleanup),
131 try_load<float>(src, flags, cleanup),
132 try_load<Math::vec4>(src, flags, cleanup),
133 try_load<Math::mat4>(src, flags, cleanup),
134 try_load<Util::String>(src, flags, cleanup),
135 try_load<Util::Guid>(src, flags, cleanup),
136 try_load<Util::Array<int>>(src, flags, cleanup),
138 try_load<Util::Array<Math::vec4>>(src, flags, cleanup),
140 try_load<Util::Array<Util::String>>(src, flags, cleanup),
143 return std::any_of(loaded.begin(), loaded.end(), [](
bool b) { return b; });
146 static handle from_cpp(
const Util::Variant& src, rv_policy policy, cleanup_list* cleanup)
noexcept {
152 template <
typename Key,
typename Value>
struct type_caster<
Util::Dictionary<Key, Value>>
153 : nanobind::detail::dict_caster<Util::Dictionary<Key, Value>, Key, Value> { };
154 template <
typename Type>
struct type_caster<
Util::Array<Type>>
155 : list_caster<Util::Array<Type>, Type> { };