I have a custom type that is basically a C++ boolean with extra functions. I need to access my C++ libraries via Python and the framework is based on Boost.
Currently I have to use ints instead of bools, because the backend can convert from int to my custom type just fine. I need to be able to convert from python's bool to my custom bool when necessary and vice versa.
Here is some code that mimicks what I have done so far:
#include <boost/python.hpp>
using namespace boost::python;
class CustomBool
{
public:
CustomBool(bool b) : is_set(b) {}
operator bool() const { return is_set; };
private:
bool is_set{false};
};
struct Example
{
CustomBool get_CustomBool(bool x)
{
return CustomBool(x);
}
bool convert_custom(bool x)
{
return bool(CustomBool(x));
}
};
BOOST_PYTHON_MODULE(bptest)
{
implicitly_convertible<CustomBool, bool>();
implicitly_convertible<bool, CustomBool>();
Py_Initialize();
class_<Example>("Example")
.def("convert_custom", &Example::convert_custom)
.def("get_CustomBool", &Example::get_CustomBool);
}
When I use it in Python I get the following:
>>> from bptest import Example
>>> ex = Example()
>>> ex.get_CustomBool(True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: No to_python (by-value) converter found for C++ type: CustomBool
I have found some string conversion examples, but I couldn't transfer their solutions to my (simpler?) problem.
The docs (https://www.boost.org/doc/libs/1_72_0/libs/python/doc/html/reference/to_from_python_type_conversion.html) are also not helpful to me, but maybe for anyone else?