Convert a pybind11::object storing a long into a ssize_t

Viewed 405

I am defining a pybind11 method that takes an object argument type (because it can take a variety of different argument types). I want to check if that object is an integer, and if so get that integer. How do I do this?

In other words, what is the pybind11 equivalent of this python code:

def method(obj):
    if isinstance(obj, int):
        value = int(obj)
        ...
    else:
        ...
void method(const pybind11::object &obj) {
    ...
}
1 Answers

Edit

I've updated my answer based on this issue showing how to use templated functions.

You can use py::cast (see the doc) and use a try catch block to cast your py::object to int.

#include <iostream>
#include <pybind11/pybind11.h>

namespace py = pybind11;

template <typename T>
void convert(const py::object stuf){
    try{
        T a = stuf.cast<T>();
        std::cout << a << std::endl;
    }catch(py::cast_error){
        std::cout << "Input object is not of known type\n";
    }
}

/* Wrapping routines with PyBind */
PYBIND11_MODULE(wrapper, m) {
        m.doc() = "";
        m.def("convert", &convert<int>, "");
        m.def("convert", &convert<float>, "");
        m.def("convert", &convert<double>, "");
        m.def("convert", &convert<bool>, "");
}


Related