Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <boost/python.hpp>
- #include <iostream>
- namespace bp = boost::python;
- std::string handle_pyerror()
- {
- namespace bp = boost::python;
- PyObject *exc, *val, *tb;
- bp::object formatted_list, formatted;
- PyErr_Fetch(&exc, &val, &tb);
- bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb));
- bp::object traceback(bp::import("traceback"));
- if (!tb) {
- bp::object format_exception_only(traceback.attr("format_exception_only"));
- formatted_list = format_exception_only(hexc, hval);
- } else {
- bp::object format_exception(traceback.attr("format_exception"));
- formatted_list = format_exception(hexc, hval, htb);
- }
- formatted = bp::str("\n").join(formatted_list);
- return bp::extract<std::string>(formatted);
- }
- void cpp_method(bp::object fn, bp::dict kwargs)
- {
- fn(*bp::tuple(), **kwargs);
- }
- BOOST_PYTHON_MODULE(foo)
- {
- bp::def("cpp_method", &cpp_method);
- }
- int main()
- {
- if (!Py_IsInitialized()) {
- Py_Initialize();
- }
- initfoo();
- try {
- bp::object main = bp::import("__main__");
- bp::object globals = main.attr("__dict__");
- bp::dict locals;
- bp::exec(
- "import foo\n"
- "def py_method(**kwargs):\n"
- " for key in kwargs.keys():\n"
- " print 'Key: ', key, ', Value: ', kwargs[key]\n"
- "kwargs = {'arg1': 1, 'arg2': 2}\n"
- "foo.cpp_method(py_method, kwargs)\n"
- , globals, locals);
- } catch (bp::error_already_set&) {
- if (PyErr_Occurred()) {
- std::cout << "Python error: " << handle_pyerror() << std::endl;
- }
- bp::handle_exception();
- PyErr_Clear();
- return -1;
- }
- Py_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement