mirror of
https://github.com/wpilibsuite/allwpilib
synced 2026-06-20 00:51:42 +00:00
[py][wpiutil] Add type caster for WPI_String (#8500)
This adds a type caster for `WPI_String` so that pybind11 can more
easily auto-convert between that and strings. This helps remove the need
to do things like
[this](f1d77244c3)
in the opmodes fixup
This commit is contained in:
@@ -120,6 +120,10 @@ types = ["wpi::util::StringMap"]
|
||||
header = "wpi_ct_string_type_caster.h"
|
||||
types = ["wpi::util::ct_string"]
|
||||
|
||||
[[tool.semiwrap.export_type_casters.wpiutil-casters.headers]]
|
||||
header = "wpi_string_type_caster.h"
|
||||
types = ["WPI_String"]
|
||||
|
||||
[[tool.semiwrap.export_type_casters.wpiutil-casters.headers]]
|
||||
header = "wpystruct.h"
|
||||
types = ["WPyStruct"]
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include "wpi/util/string.h"
|
||||
|
||||
namespace pybind11::detail {
|
||||
|
||||
template <>
|
||||
struct type_caster<WPI_String> {
|
||||
public:
|
||||
PYBIND11_TYPE_CASTER(WPI_String, _("str"));
|
||||
|
||||
bool load(handle src, bool convert) {
|
||||
if (!src) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Py_ssize_t size = -1;
|
||||
const char *str = PyUnicode_AsUTF8AndSize(src.ptr(), &size);
|
||||
if (!str) {
|
||||
PyErr_Clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
value = WPI_String(str, static_cast<size_t>(size));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static handle cast(const WPI_String& str, return_value_policy /* policy */, handle /* parent */) {
|
||||
return PyUnicode_FromStringAndSize(str.str, str.len);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace pybind11::detail
|
||||
Reference in New Issue
Block a user