Replies: 2 comments 1 reply
-
Hii @nyue! To expose C++ methods for access from an embedded Python script in your library, you should use pybind11 to create bindings. Here's a step-by-step guide to set this up with a practical example based on your
This is the straightforward way to set up and use access to the methods of your C++ class from an embedded Python script, using pybind11. If you need additional details or encounter specific issues, I'm here to help! |
Beta Was this translation helpful? Give feedback.
-
I also attempted to pass the this point as a python object but no success #include <pybind11/embed.h>
namespace py = pybind11;
using namespace py::literals;
class MyClass {
public:
MyClass() {};
double pureCMethod(double d);
void methodWithPy();
private:
double m_some_member;
};
// https://stackoverflow.com/questions/71716181/embedded-python-using-pybind11-in-c-class-how-to-call-member-function-of-c
PYBIND11_EMBEDDED_MODULE(myModule, m) {
py::class_<MyClass>(m, "MyClass")
.def("pureCMethod", &MyClass::pureCMethod);
}
// 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{};
auto myModule = py::module_::import("myModule");
auto locals = py::dict("mc"_a = this); // this pointer of class
py::exec(R"(
print("Hello From Python")
result = 23.0 + 1337
result = MyClass::pureCMethod(result) // pseudocode here. how can I do this?
print(result)
)", py::globals(), locals);
}
int main() {
MyClass mc;
mc.methodWithPy();
return 0;
} |
Beta Was this translation helpful? Give feedback.
-
This is related to another question I asked but I feel that I have did not phrased the other question clearly hence I am submitting a new question
I am developing a small library to allow user to run their own python script inside my library
My C++ node classes have functions to set/get attributes of the class
These attributes are not POD (plain old datatypes), they are objects which tracks modified time and connection to other attributes elsewhere within the framework amongst other information.
I do have methods for set/get.
What would be the pybind11 recommended way to wrap such instance method ?
What would be a call to those wrapped/extension looks like within the py_script that I will be executing within the embeded python ?
Or would I be better off doing the C++ attribute query outside of the py_script (before executing it) via the py::dict() data and retrieving the output via an the create dictionary to retrieve the results as per this
I am looking for the best practice when using pybind11.
Beta Was this translation helpful? Give feedback.
All reactions