I am writing a C++ 17 library, and a python 3 wrapper with SWIG (4.0.2). Some of the functions in the library return an std::optional<>
type. I've looking for a wrapper for C++17's std::optional<T>
for python through SWIG, but I can't find any online that can help me with my T
, an actual type (this T
is not the same T
as in template<typename T>
, it is the name of a class, in my case). This is what I've tried, and didn't work.
- I've managed to retrieve the result inside an
std::optional<>
defining two functions:
%inline %{
bool is_optional_valid(const std::optional<T>& o) { return (o ? true : false); }
T get_data(const std::optional<T>& o) { return *o; }
%}
Inside python I use these functions like this:
opt = ... # call to C++ function that returns an std::optional<>
if is_optional_valid(opt):
contents = get_graph(opt)
del opt
return contents
del opt
return None
But this returns the (probably expected) error:
swig/python detected a memory leak of type 'std::optional< T > *', no destructor found.
- Using
%template(optional_T) std::optional<T>;
does not work since SWIG returns the error:
Error: Template 'optional' undefined.
- I've been looking at typemaps at the official documentation but I can't make heads or tails out of it. And I'm not even sure that these apply in my case. For example, this github repository contains an
std_optional.i
forfloat
%typemap(in) std::optional<float> %{
if($input == Py_None) {
$1 = std::optional<float>();
}
else {
$1 = std::optional<float>((float)PyFloat_AsDouble($input));
}
%}
%typemap(out) std::optional<float> %{
if($1) {
$result = PyFloat_FromDouble(*$1);
}
else {
$result = Py_None;
Py_INCREF(Py_None);
}
%}
but I'm not sure if I can use something like this to wrap a T
(the name of a class). I tried, but I don't know what to put in the ????
.
%typemap(in) std::optional<T> %{
if($input == Py_None) {
$1 = std::optional<T>();
}
else {
$1 = std::optional<T>(T($input));
}
%}
%typemap(out) std::optional<lal::graphs::directed_graph> %{
if($1) {
$result = ????(*$1);
}
else {
$result = Py_None;
Py_INCREF(Py_None);
}
%}
Question How can I wrap a std::optional<>
with SWIG (for Python) for a T
where T
is the name of a class (if it is possible at all)? I could go about making a template class of my own with the methods given above. Something like this:
template<typename T>
class optional_wrapper {
std::optional<T> m_optional_member;
public:
// constructors...
bool has_contents() const noexcept { return (m_optional_member ? true : false); }
T get_contents() const noexcept { return *m_optional_member; }
};
and, lastly,
namespace my_library {
%template(optional_wrapper_T) optional_wrapper<T>;
}
but I don't think this is best practice for a C++ library since I'd be wrapping an existing type, with nothing new with respect to the wrapped type (please, tell me if you agree or not).
Any help will be appreciated. Thank you.