创建boost-python嵌套名称空间

发布于 2021-01-29 17:17:53

使用boost python我需要创建嵌套的名称空间。

假设我有以下cpp类结构:

namespace a
{
    class A{...}
    namespace b
    {
         class B{...}
    }
}

明显的解决方案不起作用:

BOOST_PYTHON_MODULE( a ) {
    boost::python::class_<a::A>("A")
     ...
    ;
    BOOST_PYTHON_MODULE(b){
        boost::python::class_<a::b::B>("B")
        ...
    ;
    }
}

它会导致编译时错误: linkage specification must be at global scope

有什么方法可以声明可以从Python访问的B类a.b.B吗?

关注者
0
被浏览
42
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您想要的是boost :: python ::
    scope

    Python没有“命名空间”的概念,但是您可以像命名空间一样使用类:

    #include <boost/python/module.hpp>
    #include <boost/python/class.hpp>
    #include <boost/python/scope.hpp>
    using namespace boost::python;
    
    namespace a
    {
        class A{};
    
        namespace b
        {
             class B{};
        }
    }
    
    class DummyA{};
    class DummyB{};
    
    BOOST_PYTHON_MODULE(mymodule)
    {
        // Change the current scope 
        scope a
            = class_<DummyA>("a")
            ;
    
        // Define a class A in the current scope, a
        class_<a::A>("A")
            //.def("somemethod", &a::A::method)
            ;
    
        // Change the scope again, a.b:
        scope b
            = class_<DummyB>("b")
            ;
    
        class_<a::b::B>("B")
            //.def("somemethod", &a::b::B::method)
            ;
    }
    

    然后在python中,您具有:

    #!/usr/bin/env python
    import mylib
    
    print mylib.a,
    print mylib.a.A
    print mylib.a.b
    print mylib.a.b.B
    

    所有aa.Aa.ba.b.B实际上的类,但你可以把aa.b就像命名空间-永不实际上的实例化



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看