创建升压蟒蛇嵌套命名 [英] create boost-python nested namespace
问题描述
使用boost蟒蛇,我需要创建嵌套的命名空间。
Using boost python I need create nested namespace.
假设我有以下的cpp类结构:
Assume I have following cpp class structure:
namespace a
{
class A{...}
namespace b
{
class B{...}
}
}
显而易见的解决方案不起作用:
Obvious solution not work:
BOOST_PYTHON_MODULE( a ) {
boost::python::class_<a::A>("A")
...
;
BOOST_PYTHON_MODULE(b){
boost::python::class_<a::b::B>("B")
...
;
}
}
这会导致编译时错误:链接规范必须在全局范围内
有没有什么办法,宣布将在Python访问为 a.b.B
?
Is there any way to declare class B that would be accessed from Python as a.b.B
?
推荐答案
你想要的是一个<一个href=\"http://www.boost.org/doc/libs/1_48_0/libs/python/doc/v2/scope.html\">boost::python::scope.
Python有没有命名空间的概念,但你可以使用类非常像一个命名空间:
Python has no concept of 'namespaces', but you can use a class very much like a namespace:
#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中,您有:
Then in python, you have:
#!/usr/bin/env python
import mylib
print mylib.a,
print mylib.a.A
print mylib.a.b
print mylib.a.b.B
所有 A
, AA
, AB
和 ABB
实际上是类,但是你可以把 A
和 AB
就像命名空间 - 永不实际上的实例
All a
, a.A
, a.b
and a.b.B
are actually classes, but you can treat a
and a.b
just like namespaces - and never actually instantiate them
这篇关于创建升压蟒蛇嵌套命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!