Advertisement
dan-masek

Untitled

Nov 30th, 2019
579
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <boost/python.hpp>
  2. #include <iostream>
  3. #include <set>
  4.  
  5. namespace bp = boost::python;
  6.  
  7. std::string my_function(std::set<std::string> const& set_a
  8.     , std::set<std::string> const& set_b
  9.     , int32_t number_a
  10.     , int32_t number_b)
  11. {
  12.     std::stringstream os;
  13.     os << "Set A: ";
  14.     std::for_each(begin(set_a), end(set_a), [&](auto& s) { os << s << " "; });
  15.     os << "\nSet B: ";
  16.     std::for_each(begin(set_b), end(set_b), [&](auto& s) { os << s << " "; });
  17.     os << "\nNumber A: " << number_a << "\nNumber B: " << number_b << "\n";
  18.  
  19.     return os.str();
  20. }
  21.  
  22. std::set<std::string> extract_string_set(bp::object const& python_set)
  23. {
  24.     if (!PySet_Check(python_set.ptr())) {
  25.         throw std::runtime_error("Not a set.");
  26.     }
  27.  
  28.     std::set<std::string> result;
  29.  
  30.     // Need a list to iterate over...
  31.     boost::python::list set_as_list(python_set);
  32.     for (int32_t i(0); i < len(set_as_list); ++i) {
  33.         boost::python::extract<std::string> extractor(set_as_list[i]);
  34.         if (!extractor.check()) {
  35.             throw std::runtime_error("Not a string.");
  36.         }
  37.         result.emplace(extractor());
  38.     }
  39.  
  40.     return result;
  41. }
  42.  
  43. std::string my_function_wrapper(bp::object const& python_set_a
  44.     , bp::object const& python_set_b
  45.     , int32_t number_a
  46.     , int32_t number_b)
  47. {
  48.     auto set_a(extract_string_set(python_set_a));
  49.     auto set_b(extract_string_set(python_set_b));
  50.     return my_function(set_a, set_b, number_a, number_b);
  51. }
  52.  
  53. BOOST_PYTHON_MODULE(test)
  54. {
  55.     bp::def("my_function", my_function_wrapper);
  56. }
  57.  
  58. int main()
  59. {
  60.     if (!Py_IsInitialized()) {
  61.         Py_Initialize();
  62.     }
  63.  
  64.     inittest();
  65.  
  66.     bp::object main = bp::import("__main__");
  67.     bp::object globals = main.attr("__dict__");
  68.     bp::dict locals;
  69.  
  70.     bp::exec("import test\n"
  71.         "print test.my_function({'3H', '3S'}, {'8S', '4S', 'QH', '8C', '4H'}, 2, 10000)\n"
  72.         , globals, locals);
  73.  
  74.  
  75.     Py_Finalize();
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement