我正在使用 Boost.Python 将类从 C++ 公开到 Python,例如:
class_<Point>("Point").
def(init<double, double, double>()).
add_property("X", &Point::GetX, &Point::SetX).
add_property("Y", &Point::GetY, &Point::SetY).
add_property("Z", &Point::GetZ, &Point::SetZ).
def("SetXYZ", &Point::SetPnt);
我还将一些变量公开为我的主模块的属性:
MainModule.attr("Window") = object(ptr(mainWindow));
是否可以列出模块的所有公开类和/或所有属性(在 C++ 中)?
我希望获得所有公开类的列表 ( vector<string>
):在本例中只是“Point”。公开的变量也是如此,在本例中只是“Window”。
最佳答案
使用 Python 反射功能:
从 C++ 执行一些代码:
PyRun_SimpleString("import inspect");
PyRun_SimpleString("import MyModule");
string getClassesCode =
"def GetClasses():\n"
" for name, obj in inspect.getmembers(MyModule):\n"
" if inspect.isclass(obj):\n"
" yield obj.__name__\n"
"_classes = list(GetClasses())\n";
typedef boost::python::list pylist;
object main_namespace = MainModule.attr("__dict__");
try
{
exec(getClassesCode.c_str(), main_namespace);
}
catch (error_already_set const &)
{
PyErr_Print();
}
pylist _classes = extract<pylist>(main_namespace["_classes"]);
for (int i = 0; i < len(_classes); ++i)
{
string className = extract<string>(_classes[i]);
//do whatever you need with the class name
}
关于python - Boost.Python 列出所有公开的类和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150395/