Created
February 16, 2016 16:33
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on https://wiki.python.org/moin/boost.python/EmbeddingPython