2009-12-20 10 views
4

std :: vector를 생성하는 C++ 코드를 작성했습니다.std :: vector 노출 코드 booststring ::

나는 또한 (아래)이 같은 선언 일부 데이터를 조작하는 파이썬 스크립트가 있습니다.

import numpy 
x = numpy.random.randn(1000) 
y = numpy.random.randn(1000) 

스크립트를 잘 실행할 수 있습니다. 내 C++ 코드에서 :

using namespace boost::python; 
    try{ 
      Py_Initialize(); 
      object main = import("__main__"); 
      object global(main.attr("__dict__")); 
      object result = exec_file("scatterPlot.py", global, global); 
      Py_Finalize(); 
    } 
    catch(error_already_set){ 
      PyErr_Print(); 
    } 

    return; 

저는 C++ 데이터를 파이썬으로 가져 오는 방법을 모릅니다. 나는 꽤 많이 둘러 봤지만, 결정적으로 보이는 것은 아무것도 없다.

나는 나의 C++이 작동하는 것 같다

BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ 
     boost::python::class_<std::vector<double> >("PyVec") 
     .def(boost::python::vector_indexing_suite<std::vector<double> >()); 
} 

에있는,하지만 난 이해, 그것은 단지 내가 필요한 데이터를 내 파이썬 스크립트 클래스 "PyVec"를 제공하지만. 내가 잘못?

다른 사람들이 boost::shared_ptr in a python mailing list을 사용하는 것을 보았습니다.

나는 또한 this example을 발견했지만 혼란 스러웠습니다.

내가 가야하는 가장 쉬운 접근 방식 boost_indexing_suite_ext

  • Uinsg boost::shared_ptr
  • 를 사용하여 boost::python::exec_file 방법

    1. 패스 뭔가 몇 가지 방법을 생각할 수 있는가? 어떤 접근 방식이 나에게는 분명하지 않다.

      는 여기에 내가 검토 한 좀 더 링크입니다 : from the boost website from the python website another mailing list thread

      UPDATE :이 아래

      int main(){ 
           int five_squared=0; 
           int a =3; 
           try { 
             Py_Initialize(); 
             object main_module = import("__main__"); 
             object main_namespace = main_module.attr("__dict__"); 
             main_namespace["var"]=a; 
             object ignored = exec("result = 5 ** var", main_namespace); 
             five_squared = extract<int>(main_namespace["result"]); 
           } catch(error_already_set) { 
             PyErr_Print(); 
           } 
           std::cout << five_squared << std::endl; 
           return 0; 
      } 
      

      처럼 내 파이썬 코드에 int을 전달하는 일

      하지만 위와 비슷한 방식으로 그렇게하려고 할 때 벡터를 전달하고 싶습니다. s error

      TypeError: No to_python (by-value) converter found for C++ type: std::vector >

      그래서 분명히 파이썬에게 std :: vector를 다루는 방법을 알려줄 필요가 있습니다. 나는이 코드가 도움이 될 것이라고 생각한다.

      BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ 
           boost::python::class_<std::vector<double> >("PyVec") 
           .def(boost::python::vector_indexing_suite<std::vector<double> >()); 
      } 
      

      std :: vector는 꽤 흔한 일이므로 정의 된 방법이 있어야합니다 ... 맞습니까?

  • 답변

    11

    다음 코드는 저에게 적합합니다 (Python 2.6, Boost 1.39). 이것은 BOOST_PYTHON_MODULE 라인 자체가 없으면 (그러나 벡터 정의가 class_ 인 경우를 제외하고는) 코드와 거의 같습니다. BOOST_PYTHON_MODULE은 확장 모듈을 만들 때만 사용해야합니다.

    #include <iostream> 
    #include <boost/python.hpp> 
    #include <boost/python/suite/indexing/vector_indexing_suite.hpp> 
    using namespace boost::python; 
    using namespace std; 
    
    int main() 
    { 
        vector<double> vec; 
        vec.push_back(1.2); 
        vec.push_back(3.4); 
        try { 
          Py_Initialize(); 
    
          boost::python::class_<std::vector<double> >("PyVec") 
          .def(boost::python::vector_indexing_suite<std::vector<double> >()); 
    
          object main_module = import("__main__"); 
          object globals = main_module.attr("__dict__"); 
          globals["var"]=vec; 
          object ignored = exec("result = sum(var)", globals, globals); 
          double result = extract<double>(globals["result"]); 
          std::cout << result << std::endl; 
        } catch(error_already_set) { 
          PyErr_Print(); 
        } 
        return 0; 
    } 
    
    +0

    정말 대단합니다. – devin

    +0

    더 많은 객체 지향 방법이 있습니까? 실행을 위해 파이썬 문자열을 전달하는 대신 벡터가 sum이 처리하고 객체를 생성 할 수있는 유형으로 벡터를 변환합니다. sum = main_module ("sum"); ...? – SullX

    2

    올바르게 이해하고 있는지 잘 모르겠습니다. std::vector<double>을 저장할 수있는 "PyVec"클래스를 내 보낸 후에는 입력 또는 리턴 유형으로 벡터를 가져 오는 모든 C++ 함수를 내보낼 수 있습니다. 그래서 당신은 벡터를 C++로 채우고이 데이터를 파이썬에서 인터페이스 타입 "PyVec"으로 접근 할 수 있습니다.

    +0

    예.하지만 파이썬 스크립트에서 벡터를 채우려면 어떻게해야합니까? – devin

    +0

    인덱싱 수트는'__setitem__'과'__getitem__'을 정의합니다. 그래서 파이썬 안에서는 벡터를 첨자 연산자 []로 채울 수 있습니다. boost :: python 인덱싱 슈트의 벡터 예제를 보았습니까? http://www.boost.org/doc/libs/1_41_0/libs/python/test/vector_indexing_suite.py – rafak

    +0

    나는 그다지 따르지 않는다 ... 나는 그것이 비슷한 것을하는 약간의 근원을 가장 많이 보는 것을 도울 것이라고 생각한다. 내가하고 싶은 걸로 – devin

    관련 문제