0

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());
}
2
  • 1
    Maybe, you'll need to pass "this" as an argument to the python code you run and wrap the c++ class first inside an embedded module pybind11.readthedocs.io/en/stable/advanced/… Commented Apr 2, 2022 at 13:53
  • 1
    However IMO it will be easier to do this from Python - you can inherit c++ classes in python code and then add Pythonic methods to the child class. Commented Apr 2, 2022 at 13:56

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.