I am looking for a simple way to expose a C++ class instance to a python embedded interpreter.
For reference, here is how you can achieve this using pybind11:
#include
#include
namespace py = pybind11;
// Define C++ class "Foo"
class Foo {
std::string s_;
public:
Foo(const std::string &s) : s_(s) {}
void doSomething() { std::cout << s_ << std::endl; }
};
typedef std::shared_ptr FooPtr;
// Define Python module "bar" and Python class "bar.Foo" wrapping the C++ class
PYBIND11_MODULE(bar, m) {
py::class_(m, "Foo")
.def("doSomething", &Foo::doSomething);
}
int main(int argc, char **argv)
{
// Create a C++ instance of Foo
FooPtr foo = std::make_shared("Hello, World!");
// Initialize Python interpreter and import bar module
PyImport_AppendInittab("bar", PyInit_bar);
Py_Initialize();
PyRun_SimpleString("import bar");
// Make C++ instance accessible in Python as a variable named "foo"
py::module main = py::module::import("__main__");
main.attr("foo") = foo;
// Run some Python code using foo
PyRun_SimpleString("foo.doSomething()");
// Finalize the Python interpreter
Py_Finalize();
return 0;
}