Skip to content

Instantly share code, notes, and snippets.

@mcleary
Created February 16, 2016 16:33
Show Gist options
  • Save mcleary/073a9bc6db4e486fbf3d to your computer and use it in GitHub Desktop.
Save mcleary/073a9bc6db4e486fbf3d to your computer and use it in GitHub Desktop.
This is a code snippet that exports an existing Cpp object to python
#include <iostream>
#include <string>
#include <boost/python.hpp>
using namespace std;
using namespace boost::python;
class World
{
private:
string name;
public:
World() {}
void set(string name) {
this->name = name;
}
void greet() {
cout << "hello, I am " << name << endl;
}
};
typedef std::shared_ptr< World > world_ptr;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set);
}
int main()
{
Py_Initialize();
inithello();
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
std::shared_ptr<World> w = std::make_shared<World>();
main_namespace["world"] = ptr(w.get());
object ignored = exec("world.set('python')\n"
"world.greet()", main_namespace, main_namespace);
return 0;
}
@mcleary
Copy link
Author

mcleary commented Feb 16, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment