-
I have a class in which I have a method ::compute() which I am embedding Python Within that embedding I would like the Python session to have access to call the C++ class methods to set/get information. I am able to do the embedding, however, I am unable to setup a module to access the class' methods as extending via PYBIND11_EMBEDDED_MODULE creates static functions. Is this possible with pybind11 or am I looking at the problem wrongly and hence not being able to find a solution ? #include <iostream>
#include <pybind11/embed.h>
PYBIND11_EMBEDDED_MODULE(fast_calc, m)
{
// `m` is a `py::module_` which is used to bind functions and classes
m.def("add", [](int i, int j) { return i + j; });
}
class MyClass
{
public:
MyClass()
: _quantity(0){
};
virtual ~MyClass(){};
int numComponents() { return _quantity; };
void compute()
{
pybind11::scoped_interpreter guard{};
auto fast_calc = pybind11::module_::import("fast_calc");
std::string script =R"(
print(dir(fast_calc))
print('MyClass::compute()')
kwargs = dict(name = 'World', number = 42)
message = 'Hello, {name}! The answer is {number}'.format(**kwargs)
print(message)
)";
std::cout << "script = " << script << std::endl;
pybind11::exec(script);
}
private:
int _quantity;
};
int main()
{
MyClass mc;
mc.compute();
return 0;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Yes. You can do something like PYBIND11_EMBEDDED_MODULE(fast_calc, m)
{
py::class_<MyClass>(m, "PythonSideMyClassName")
.def(py::init<>())
.def("numComponents", &MyClass::numComponents)
} https://pybind11.readthedocs.io/en/stable/advanced/classes.html |
Beta Was this translation helpful? Give feedback.
PythonSideMyClassName
. What I meant with that is how you want to address this class in your Python script. The name you write in double-quotes is how you would see it from python. If you just want the same name, that is also fine.MyClass::compute()
from python, you should add that to the list of methods exposed in thePYBIND11_EMBEDDED_MODULE
. But, that doesn't make sense in this case, becauseMyClass::compute()
…