Advertisement
dan-masek

Untitled

Oct 3rd, 2018
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <boost/python.hpp>
  2. #include <iostream>
  3.  
  4. namespace bp = boost::python;
  5.  
  6. std::string handle_pyerror()
  7. {
  8.     namespace bp = boost::python;
  9.  
  10.     PyObject *exc, *val, *tb;
  11.     bp::object formatted_list, formatted;
  12.     PyErr_Fetch(&exc, &val, &tb);
  13.     bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb));
  14.     bp::object traceback(bp::import("traceback"));
  15.     if (!tb) {
  16.         bp::object format_exception_only(traceback.attr("format_exception_only"));
  17.         formatted_list = format_exception_only(hexc, hval);
  18.     } else {
  19.         bp::object format_exception(traceback.attr("format_exception"));
  20.         formatted_list = format_exception(hexc, hval, htb);
  21.     }
  22.     formatted = bp::str("\n").join(formatted_list);
  23.     return bp::extract<std::string>(formatted);
  24. }
  25.  
  26. void cpp_method(bp::object fn, bp::dict kwargs)
  27. {
  28.     fn(*bp::tuple(), **kwargs);
  29. }
  30.  
  31. BOOST_PYTHON_MODULE(foo)
  32. {
  33.     bp::def("cpp_method", &cpp_method);
  34. }
  35.  
  36. int main()
  37. {
  38.     if (!Py_IsInitialized()) {
  39.         Py_Initialize();
  40.     }
  41.  
  42.     initfoo();
  43.  
  44.     try {
  45.         bp::object main = bp::import("__main__");
  46.         bp::object globals = main.attr("__dict__");
  47.         bp::dict locals;
  48.  
  49.         bp::exec(
  50.             "import foo\n"
  51.             "def py_method(**kwargs):\n"
  52.             "    for key in kwargs.keys():\n"
  53.             "        print 'Key: ', key, ', Value: ', kwargs[key]\n"
  54.             "kwargs = {'arg1': 1, 'arg2': 2}\n"
  55.             "foo.cpp_method(py_method, kwargs)\n"
  56.             , globals, locals);
  57.  
  58.     } catch (bp::error_already_set&) {
  59.         if (PyErr_Occurred()) {
  60.             std::cout << "Python error: " << handle_pyerror() << std::endl;
  61.         }
  62.         bp::handle_exception();
  63.         PyErr_Clear();
  64.         return -1;
  65.     }
  66.  
  67.     Py_Finalize();
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement