COMPUTER

C++ cutom vector to Python

cherry1031 2013. 10. 15. 15:40

부스트 사용해서 래퍼 작성

c++에서 struct의 vector인 애를 받아서 python 의 list로 변환해주기



1.C++벡터를 파이썬 리스트로 변환

http://stackoverflow.com/questions/6157409/stdvector-to-boostpythonlist





2. 원하는 스트럭트의 wrapper를 작성


C++ struct to Python object

(원문 http://boost.2283326.n4.nabble.com/Boost-Python-to-python-converter-td4529040.html )



#include <boost/python.hpp> 
#include <string> 
struct Unit 

   int health; 
   std::string name; 
   std::string type; 
   std::pair<int,int> coord; 
}; 

struct Unit_to_python 

   static PyObject* convert(Unit const& unit) 
   { 
      return boost::python::incref(boost::python::object(unit).ptr()); 
   } 
}; 

BOOST_PYTHON_MODULE(game) 

   boost::python::class_<Unit>("Unit") 
      .def_readwrite("health", &Unit::health) 
      .def_readwrite("name", &Unit::name) 
      .def_readwrite("type", &Unit::type) 
      .def_readwrite("coord", &Unit::coord) 
   ; 


int main(int argc, char** argv) 

   Py_Initialize(); 
   boost::python::to_python_converter<Unit, Unit_to_python>(); 
   Unit unit1; 
   unit1.health = 100; 
   unit1.name = "Tank"; 
   unit1.type = "Armor"; 
   boost::python::object foo(unit1); // crash: stack overflow 
   return 0; 

___