Search code examples
pythonc++pybind11

how to make bind a map on pybind11


i am working on a backtester for crypto in cpp, but the backend is on python and flask, i try to use pybind11 in order to make the cpp work on the backend, here is my bind code

namespace py = pybind11;
PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);

PYBIND11MODULE(backtester, m)
{

    py::class<BT::Backtester>(m, "Backtester");
    m.def(py::init<py::bind_map<std::map<std::string, double>>());
   
}

when i compile the bind i have this error

enter image description here

what can it be? how do i solve the error? thanks in advance


Solution

  • py::bind_map tells pybind11 to bind a type, it doesn't affect the arguments that py::init gets. This is probably what you wanted to do:

    namespace py = pybind11;
    PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
    
    PYBIND11_MODULE(backtester, m)
    {
        py::bind_map<std::map<std::string, double>>(m, "StringDoubleMap");
        py::class<BT::Backtester>(m, "Backtester");
        m.def(py::init<std::map<std::string, double>>());
    }
    

    Like I said in a comment, you should probably just include pybind11/stl.h and let pybind11 handle the dict/map conversion.