python - Boost.Python 列出所有公开的类和属性

标签 python c++ boost

我正在使用 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/

相关文章:

c++ - 从另一个线程修改 vector 中的指针数据是否安全?

python - 在堆叠条形图中包含 Bokeh 工具提示

c++ - 将 QComboBox 文本写入文件

c++ - 将ZeroMQ与Boost::ASIO一起使用

c++ - 如何在运行时设置 (Win32 API) Picture Control 的图像?

c++ - 计算飞行距离的程序

c++ - boost::chrono::time_point<> 和 boost::chrono::steady_clock::time_point 之间的区别

python - 为什么 Twine 1.9.1 仍在上传到旧版 PyPi?

python - 在 Kivy 和 Python 之间旋转图像的行为

python - 属性错误 : 'Recognizer' object has no attribute 'recognize'