【Python】解析CPP类定义代码,获取UML类图信息

本文介绍如何使用Python的CppHeaderParser库解析C++头文件,提取类的属性和成员函数信息,包括访问权限和参数类型,以支持UML类图绘制。

参考 & 鸣谢


目的

  • 解析CPP头文件中的类定义,获取UML中的属性。用于画UML类图。如下所示格式,图片来源-链接

  • 即获取,类名,成员函数,成员方法。
    • 后置函数返回值、参数类型。
    • +、-、# 区分不同的访问权限,public,private,protected。
  • 使用Python的CppHeaderPaser库完成CPP文件中类定义解析。

代码实现

import sys
import CppHeaderParser
import os
import shutil
import os
import re


type_hash = {'private' : '- ','protected' : '# ','public' : '+ '}

def get_mem_var(parse_conent,cur_class,target_type):
    for class_private_mem_var in parse_conent.classes[cur_class]['properties'][target_type]:
        # 组装private属性
        tmp_str = type_hash[target_type] + class_private_mem_var['name'] + ' : ' + class_private_mem_var['type']
        print(tmp_str)

def get_mem_func(parse_conent,cur_class,target_type):
    # 遍历方法 - public
    for class_mem_func in parse_conent.classes[class_name]['methods'][target_type]:
        tmp_str = ''
        tmp_str = type_hash[target_type] + class_mem_func['name'] + '('
        # 遍历函数参数
        if len(class_mem_func['parameters']):  # 有参数
            p_cnt = len(class_mem_func['parameters'])
            tmp_cnt = 0
            for one_param in class_mem_func['parameters']:  # 一个函数的多个参数,分多行
                tmp_cnt = tmp_cnt + 1
                tmp_str = tmp_str + one_param['name'] + " : " + one_param['type']
                if tmp_cnt != p_cnt:
                    tmp_str = tmp_str + ' , '
        tmp_str = tmp_str + ')' + " : "

        # 组装返回值
        tmp_str = tmp_str + class_mem_func['rtnType']
        print(tmp_str)



if __name__ == '__main__':
    while True:
        # file = input("文件路径: ")
        file = input("请输入头文件路径: ")
        dest_dir_path = './'
        # 源文件是否存在
        if os.path.exists(file):
            print()
            # 复制文件
            shutil.copy2(file,dest_dir_path)
            # 新的目标路径
            (file_path,file_name) = os.path.split(file)
            file = dest_dir_path + file_name
            # 拷贝的临时文件是否存在
            if os.path.exists(file):
                # 去除新文件中的中文
                tmp_new_content = ''
                with open(file,"r+",encoding='utf-8') as f:
                    old_file_content = f.read()
                    # print(old_file_content)
                    tmp_new_content = re.sub('[\u4e00-\u9fa5]','',old_file_content)
                # 重新打开,清空写入
                with open(file,"w+",encoding='utf-8') as f:
                    f.write(tmp_new_content)

                # 解析
                parse_conent = CppHeaderParser.CppHeader(file)
                # 遍历每个解析到的类
                for class_name in parse_conent.classes.keys():
                    # 当前类
                    print("###################################################")
                    print(class_name + '\n')
                    # 获取属性 - private - protected - public
                    get_mem_var(parse_conent, class_name, 'private')
                    get_mem_var(parse_conent, class_name, 'protected')
                    get_mem_var(parse_conent, class_name, 'public')
                    print()
                    # 获取方法 - private - protected - public
                    get_mem_func(parse_conent, class_name, 'private')
                    get_mem_func(parse_conent, class_name, 'protected')
                    get_mem_func(parse_conent, class_name, 'public')

                    # 分割线,划分不同类
                    print()
                    print("###################################################")
            else:
                print("拷贝文件不存在")
        else:
            print("源文件文件不存在")


        # 结束后删除临时文件
        os.remove(file)




使用

获取文件路径

  • shift + 右键选择文件,点击复制文件路径,即可获取该文件的绝对路径。
  • 或者使用VSCode,Clion,右键选择文件,复制文件路径。

启动程序,输入路径即可。

  • 这个类内容太多了,这里就截取了一部分。
  • 类名,成员变量,成员方法之间用空行隔开。多个类直接用#隔开。


存在问题

  • 部分新特性解析错误,例如:
  // 定时触发的回调函数
  std::function<void()> tick_;

  // 处理消息的回调函数
  std::function<Status(proto::MessagePtr)> step_;

会识别为成员函数。


  • 不完善的地方
    • 构造函数析构函数的,返回值类型,为void,应该为空
    • 析构函数检测不到波浪号~


  • CppHeaderParser打开文件编码问题(已经解决),会提示如下报错
   headerFileStr = "".join(fd.readlines())
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8c in position 830: illegal multibyte sequence

原因: 给定文件中有GBK无法表示的字符。例如中文。
解决方法(已在上述代码中使用): 拷贝文件,去掉其中的中文字符,保存文件,用GBK编码集保存。

#include <iostream> // 输入输出流库,用于cin/cout操作 #include <string> // 字符串处理库 #include <cctype> // 字符处理函数库(虽然本例未直接使用,但通常用于输入验证) using namespace std; // 使用标准命名空间,避免重复写std:: // 课题 - 表示单个课题的实体 class Topic { public: string title; // 课题标题(字符串型) bool isSelected; // 课题是否已被选择(布尔型) string selectedBy; // 选择该课题的学生姓名(字符串型) // 构造函数 - 创建课题对象时自动调用 Topic(string t) : title(t), isSelected(false), selectedBy("") {} // 参数t: 传入的课题标题 // : 后是成员初始化列表 // title(t) - 将成员title初始化为传入的t // isSelected(false) - 初始状态设为未选择 // selectedBy("") - 初始选择者设为空字符串 }; // 定义结束 // 课题管理系统 - 管理课题集合 class TopicManager { private: Topic** topics; // 指向课题指针数组的指针(动态二维数组) int capacity; // 当前数组的容量(可容纳的最大课题数) int size; // 当前实际存储的课题数量 // 调整数组容量的私有方法 void resize(int newCapacity) { // 创建新容量的指针数组 Topic** newTopics = new Topic*[newCapacity]; // 将原数组内容复制到新数组 for (int i = 0; i < size; ++i) { newTopics[i] = topics[i]; // 复制指针(浅拷贝) } // 释放原数组内存 delete[] topics; // 先删除指针数组 topics = newTopics; // 将topics指向新数组 capacity = newCapacity; // 更新容量值 } public: // 构造函数 - 初始化管理系统 TopicManager() : topics(nullptr), capacity(0), size(0) {} // 初始化列表: // topics(nullptr) - 初始化为空指针 // capacity(0) - 初始容量为0 // size(0) - 初始课题数为0 // 析构函数 - 对象销毁时自动调用,释放内存 ~TopicManager() { // 遍历所有课题对象,释放每个课题的内存 for (int i = 0; i < size; ++i) { delete topics[i]; // 删除每个课题对象 } delete[] topics; // 删除课题指针数组 } // 增加课题的公共方法 void addTopic(string title) { // 检查是否需要扩容 if (size >= capacity) { // 计算新容量:初始为2,之后倍增 int newCapacity = (capacity == 0) ? 2 : capacity * 2; resize(newCapacity); // 调用扩容方法 } // 在数组末尾创建新课题 topics[size] = new Topic(title); // 动态分配内存 size++; // 课题数量增加 cout << "课题已添加: " << title << endl; // 操作反馈 } // 删除课题的公共方法 void deleteTopic(int index) { // 检查索引有效性 if (index >= 0 && index < size) { cout << "课题已删除: " << topics[index]->title << endl; // 反馈 delete topics[index]; // 释放该课题的内存 // 移动后续元素填补空缺 for (int i = index; i < size - 1; ++i) { topics[i] = topics[i + 1]; // 指针前移 } size--; // 课题数量减少 } else { cout << "无效的课题索引。" << endl; // 错误提示 } } // 修改课题的公共方法 void modifyTopic(int index, string newTitle) { // 检查索引有效性 if (index >= 0 && index < size) { topics[index]->title = newTitle; // 更新标题 cout << "课题已修改: " << newTitle << endl; // 反馈 } else { cout << "无效的课题索引。" << endl; // 错误提示 } } // 显示所有课题的公共方法 void displayTopics() { cout << "当前课题列表:" << endl; // 标题 // 遍历所有课题 for (int i = 0; i < size; ++i) { // 输出序号和标题 cout << i + 1 << ". " << topics[i]->title; // 如果课题已被选择,显示选择者信息 if (topics[i]->isSelected) { cout << " (已选择 by " << topics[i]->selectedBy << ")"; } cout << endl; // 换行 } } // 选择课题的公共方法 void selectTopic(int index, string studentName) { // 检查索引有效性 if (index >= 0 && index < size) { // 检查课题是否已被选择 if (!topics[index]->isSelected) { topics[index]->isSelected = true; // 标记为已选择 topics[index]->selectedBy = studentName; // 记录选择者 cout << "你已选择课题: " << topics[index]->title << endl; // 反馈 } else { // 课题已被选择时显示选择者信息 cout << "该课题已被选择 by " << topics[index]->selectedBy << endl; } } else { cout << "无效的课题索引。" << endl; // 错误提示 } } // 查看已选课题的公共方法 void viewSelectedTopics() { cout << "已选课题列表:" << endl; // 标题 // 遍历所有课题 for (int i = 0; i < size; ++i) { // 只显示已被选择的课题 if (topics[i]->isSelected) { // 输出课题标题和选择者 cout << topics[i]->title << " by " << topics[i]->selectedBy << endl; } } } }; // 菜单显示函数 void menu() { // 输出菜单选项 cout << "Menu:" << endl; cout << "1. 添加课题" << endl; cout << "2. 删除课题" << endl; cout << "3. 修改课题" << endl; cout << "4. 显示所有课题" << endl; cout << "5. 选择课题" << endl; cout << "6. 查看已选课题" << endl; cout << "7. 退出系统" << endl; } // 获取有效整数输入的函数 int getValidIntInput() { int value; // 存储输入值的变量 // 循环直到获得有效输入 while (!(cin >> value)) { cout << "输入无效,请重新输入: "; // 错误提示 cin.clear(); // 清除错误状态 cin.ignore(10000, '\n'); // 忽略缓冲区中的错误输入 } return value; // 返回有效整数 } // 主函数 - 程序入口点 int main() { TopicManager manager; // 创建课题管理器对象 int choice; // 存储用户选择的变量 // 主循环 do { menu(); // 显示菜单 cout << "请选择操作: "; choice = getValidIntInput(); // 获取有效整数输入 cin.ignore(); // 忽略换行符,防止影响后续输入 // 根据用户选择执行操作 switch (choice) { case 1: { // 添加课题 string title; cout << "请输入课题名称: "; getline(cin, title); // 读取整行输入 manager.addTopic(title); // 调用添加方法 break; } case 2: { // 删除课题 cout << "请输入要删除的课题索引: "; int index = getValidIntInput(); // 获取索引 manager.deleteTopic(index - 1); // 调用删除方法(索引-1转换为0-based) break; } case 3: { // 修改课题 cout << "请输入要修改的课题索引: "; int index = getValidIntInput(); // 获取索引 cin.ignore(); // 清除换行符 string newTitle; cout << "请输入新的课题名称: "; getline(cin, newTitle); // 读取新标题 manager.modifyTopic(index - 1, newTitle); // 调用修改方法 break; } case 4: // 显示所有课题 manager.displayTopics(); // 调用显示方法 break; case 5: { // 选择课题 cout << "请输入要选择的课题索引: "; int index = getValidIntInput(); // 获取索引 cin.ignore(); // 清除换行符 string studentName; cout << "请输入你的名字: "; getline(cin, studentName); // 读取学生姓名 manager.selectTopic(index - 1, studentName); // 调用选择方法 break; } case 6: // 查看已选课题 manager.viewSelectedTopics(); // 调用查看方法 break; case 7: // 退出系统 cout << "退出系统。" << endl; // 退出提示 break; default: // 无效选择处理 cout << "无效的选择。" << endl; break; } cout << endl; // 添加空行,使界面更清晰 } while (choice != 7); // 当选择7时退出循环 return 0; // 程序正常结束 }生成UML
最新发布
06-16
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半生瓜のblog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值