2013-03-01 1 views
1

enum의 중첩 된 일부 C++ 클래스를 Python에 노출시키고 있습니다. boost.orgwiki.python.org에있는 예제 문서를 보면 전역/모듈 범위로 돌아가려면 일단 입력 된 후에는 범위를 벗어나는 방법을 볼 수 없습니다. 대신 후속 범위는 이전 범위 내에서 중첩됩니다.Boost.Python - 모듈 스코프를 다시 입력하는 방법은 무엇입니까?

$ g++ -fPIC -shared scope.cpp -o foo.so -lpython2.7 -I/usr/include/python2.7 -lboost_python 
$ python -c 'import foo; print "Bar" in dir(foo)' 
False 
$ python -c 'import foo; print "Bar" in dir(foo.Foo)' 
True 

편집 :

데 내가 같은 결과에 global; 다양한 것들 라인,하지만 모든 것을 변화 시도했습니다

#include <boost/python.hpp> 

class Foo 
{ 
public: 
    enum Choose { eFoo, eBar }; 

    /* Default constructor with enum as required argument */ 
    Foo(Choose choice): m_choice(choice) {} 
    ~Foo() {} 

    Choose get() const { return m_choice; } 

private: 
    const Choose m_choice; 

}; 


class Bar 
{ 
}; 

BOOST_PYTHON_MODULE(foo) 
{ 
    using namespace boost::python; 
    scope global; 

    /* Define Foo class, and a scope to go with it. */ 
    scope in_Foo = class_<Foo> 
     ("Foo", init<Foo::Choose>()) 
     .def("rovalue", &Foo::get) 
     ; 

    /* Expose 'Choose' enum as Foo.Choose */ 
    enum_<Foo::Choose>("Choose") 
     .value("Foo", Foo::eFoo) 
     .value("Bar", Foo::eBar) 
     ; 

    /* How to get back to module scope?? */ 
    global; 
    scope(); 

    /* This currently is exposed as Foo.Bar, but should just be Bar */ 
    class_<Bar>("Bar", init<>()) 
     ; 
} 

: 예를 들어

위의 예제에서 올바른 대답은를 사용하는 것입니다.을 눌러 모듈 수준 범위로 되돌립니다. 실제로 이것은 위의 예에서 작동합니다. 내 실제 응용 프로그램에서 사용할 때 불행하게도하지만, 내가

#include <boost/python.hpp> 
using namespace boost; 
BOOST_PYTHON_MODULE(foo) 
{ 
    python::scope module_level; 
    /* .... */ 
    python::scope python::within(module_level); 
    /* ... */ 
} 

컴파일 에러 .. 컴파일 오류 : 아마도

error: invalid use of qualified-name 'boost::python::within' 

답변

5
아이러니하게도

, 그 자신의 좋은 너무 영리이 수행 할 수 있습니다 C++ 범위를 사용합니다. boost::python::scope 문서는 scope 개체의 수명이 끝날 때, 현재 범위가 scope 객체의 구축되기 전의으로 되돌아갑니다 상태.

BOOST_PYTHON_MODULE(foo)    // set scope to foo 
{ 
    using namespace boost::python; 
    { 
    scope in_Foo = class_<Foo>  // define foo.Foo and set scope to foo.Foo 
     ("Foo", init<Foo::Choose>()) 
     .def("rovalue", &Foo::get) 
     ; 

    enum_<Foo::Choose>("Choose")  // define foo.Foo.Choose 
     .value("Foo", Foo::eFoo) 
     .value("Bar", Foo::eBar) 
     ; 
    }         // revert scope, setting scope to foo 

    class_<Bar>("Bar", init<>())  // define foo.Bar 
     ; 
} 

scope 객체가 자신의 수명이 다른 수단을 통해 관리 한 수 있지만

, 나는 C++ 범위 내에서 자동 변수로 scope 객체를 사용하여 C++ 네임 스페이스에 몇 가지 병렬 처리를 제공 찾을 수 있습니다.

+0

감사! 저는 여전히 C++에 대한 완전한 초보자입니다. 그래서이 교활한 언어 기능들이 많이 필요합니다. 이것은 잘 작동하지만 예상대로! –

+0

덜 "아이러니하게도, 아마도 너무 똑똑하다"며 "이것은이 오브젝트의 의도와 정확히 일치합니다." – Barry

관련 문제