goaran
goaran

Reputation: 495

embedded python using pybind11 in c++ class: how to call member function of c++ class from python

I've a class with a method (MyClass::methodWithPy) that can be customized by some python script using embedded pybind11, which so far works.

Inside the python script I need to somehow call methods of the c++ class. Is this possible somehow?

This is what I have so far, but I do not know how to call the class method from within python.

class MyClass 
{
  public:
    MyClass();

    double pureCMethod(double d);
    void methodWithPy(); 

  private:
    double m_some_member;
};

// method of the c++ class that has acess to members and does some computation
double MyClass::pureCMethod(double d) 
{
    // here we have some costly computation
    return m_some_member*d;
}

// 2nd method of the c++ class that uses embedded python
void MyClass::methodWithPy()
{
    namespace py = pybind11;
    using namespace py::literals;

    py::scoped_interpreter guard{};

    py::exec(R"(
        print("Hello From Python")
        result = 23.0 + 1337
        result = MyClass::pureCMethod(reslut) // pseudocode here. how can I do this? 
        print(result)
    )", py::globals());
}

Upvotes: 0

Views: 1125

Answers (1)

goaran
goaran

Reputation: 495

Thanks @unddoch for the link. That got me to the answer. PYBIND11_EMBEDDED_MODULE was the part I was missing.

First you need to define an embedded python module containing the class and the methos:

PYBIND11_EMBEDDED_MODULE(myModule, m)
{
    py::class_<MyClass>(m, "MyClass")
        .def("pureCMethod", &MyClass::pureCMethod);
}

Then pass the class to python (import the module first)

auto myModule = py::module_::import("myModule");
auto locals = py::dict("mc"_a=this); // this pointer of class

And now its possible to access the member methods from python

py::exec(R"(
print("Hello From Python")
print(mc.pureCMethod(23))
)", py::globals(), locals);

Upvotes: 1

Related Questions