记录java调用eclipse cdt 解析c++文件

news/2025/9/26 8:58:35/文章来源:https://www.cnblogs.com/sunshine99/p/19112471

环境:

jdk1.8

eclipse cdt  9.11.1

需求: 

java 解析c++中的类,属性类型,属性名称,函数,函数参数,返回值。

注意点: 

如果你是外网编码,移植依赖和代码到内网的时候

运行可能出现 class not found xxxx ,  这个依赖其实是对的。

解决办法: 

将内网的maven的setting.xml 与外网的仓库地址相同就能解决

具体需要一致内容地点: 

      <mirror><id>aliyunmaven</id><mirrorOf>*</mirrorOf><name>阿里云公共仓库</name><url>https://maven.aliyun.com/repository/public</url></mirror>

  

依赖: 

1. cdt 下载
https://archive.eclipse.org/tools/cdt/releases/9.11/cdt-9.11.1/

2. pom添加依赖: 

<dependencies><!-- CDT 核心 --><dependency><groupId>org.eclipse.cdt</groupId><artifactId>org.eclipse.cdt.core</artifactId><version>9.11.1</version><scope>system</scope><systemPath>${project.basedir}/libs/org.eclipse.cdt.core_6.11.1.202006011430.jar</systemPath></dependency><!-- Eclipse runtime 必要依赖 --><dependency><groupId>org.eclipse.platform</groupId><artifactId>org.eclipse.core.runtime</artifactId><version>3.13.0</version></dependency><dependency><groupId>org.eclipse.platform</groupId><artifactId>org.eclipse.core.jobs</artifactId><version>3.9.3</version></dependency><dependency><groupId>org.eclipse.platform</groupId><artifactId>org.eclipse.core.contenttype</artifactId><version>3.6.0</version></dependency><dependency><groupId>org.eclipse.platform</groupId><artifactId>org.eclipse.equinox.common</artifactId><version>3.9.0</version></dependency><!-- 日志服务 --><dependency><groupId>org.eclipse.platform</groupId><artifactId>org.eclipse.equinox.supplement</artifactId><version>1.8.0</version></dependency></dependencies>

 

解析代码: 

package org.example;import org.eclipse.cdt.core.dom.ast.*;
import org.eclipse.cdt.core.dom.ast.cpp.*;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.*;import java.util.HashMap;public class CDTParseExample {public static void main(String[] args) throws Exception {// 1. 指定要解析的头文件路径String filePath = "C:\\Users\\dell\\AppData\\Roaming\\JetBrains\\IntelliJIdea2025.2\\extensions\\xxxxxx.h";FileContent fileContent = FileContent.createForExternalFileLocation(filePath);// 2. 模拟 include / 宏定义信息  HashMap<String, String> macros = new HashMap<>();macros.put("__cplusplus", "1");macros.put("XXXXX_DLL", "");  // 避免 class XXXXX_DLL 出错macros.put("FRDTOMOON_ID", "int");  // 如果有类似 typedef 也要补macros.put("CAbstractEntity", "int"); // 临时占位macros.put("C_DBIDriver", "int");macros.put("CTableQuery", "int");IScannerInfo scannerInfo = new ScannerInfo(macros, new String[] {"C:\\Users\\dell\\AppData\\Roaming\\JetBrains\\IntelliJIdea2025.2\\extensions"});IncludeFileContentProvider fileContentProvider = IncludeFileContentProvider.getEmptyFilesProvider();// 3. 创建 TranslationUnitIASTTranslationUnit translationUnit = GPPLanguage.getDefault().getASTTranslationUnit(fileContent,scannerInfo,fileContentProvider,null,ITranslationUnit.AST_PARSE_INACTIVE_CODE,new DefaultLogService());// 4. 遍历 AST,找到类定义// 假设你已经有 IASTTranslationUnit tu(通过 GPPLanguage.getDefault().getASTTranslationUnit(...))translationUnit.accept(new ASTVisitor(true) {{// 一定要打开这些 flagshouldVisitDeclarations = true;shouldVisitDeclSpecifiers = true;shouldVisitNamespaces = true;// 如果头文件内有宏可能屏蔽成员,考虑打开:
//                 includeInactiveNodes = true;}// 处理命名空间(可选)@Overridepublic int visit(ICPPASTNamespaceDefinition namespaceDefinition) {System.out.println("namespace: " + (namespaceDefinition.getName() != null ? namespaceDefinition.getName() : "<anon>"));// namespace 内部声明也会单独触发 visit(IASTDeclaration),// 这里可以选择直接遍历 namespaceDefinition.getDeclarations() 或交由 visit(IASTDeclaration) 处理。return PROCESS_CONTINUE;}@Overridepublic int visit(IASTProblem problem) {System.out.println("Parser problem: " + problem.getMessage()+ " at " + problem.getFileLocation().getFileName()+ ":" + problem.getFileLocation().getStartingLineNumber());return PROCESS_CONTINUE;}// 处理所有声明(包括 class/struct 的声明)@Overridepublic int visit(IASTDeclaration declaration) {// 只关心简单声明(class/struct 在 simpleDecl 的 declSpec 中)if (declaration instanceof IASTSimpleDeclaration) {IASTSimpleDeclaration simpleDecl = (IASTSimpleDeclaration) declaration;IASTDeclSpecifier declSpec = simpleDecl.getDeclSpecifier();// 如果这是 class/struct 的定义(复合类型)if (declSpec instanceof ICPPASTCompositeTypeSpecifier) {ICPPASTCompositeTypeSpecifier classSpec = (ICPPASTCompositeTypeSpecifier) declSpec;System.out.println("Class/Struct: " + classSpec.getName());// 关键点:成员就在 classSpec.getMembers()IASTDeclaration[] members = classSpec.getMembers();for (IASTDeclaration member : members) {// 我们主要关心成员变量(IASTSimpleDeclaration 且 declarators 非空 且 不是函数)if (member instanceof IASTSimpleDeclaration) {IASTSimpleDeclaration memberDecl = (IASTSimpleDeclaration) member;IASTDeclarator[] decs = memberDecl.getDeclarators();if (decs != null && decs.length > 0) {// 如果 declarator 不是函数 declarator,则为字段if (!(decs[0] instanceof IASTFunctionDeclarator)) {String type = memberDecl.getDeclSpecifier() != null ?memberDecl.getDeclSpecifier().getRawSignature() : "<unknown>";for (IASTDeclarator d : decs) {// 安全取名(有时 getName() 为空)String name = (d.getName() != null) ? d.getName().toString() : d.getRawSignature();System.out.println("  field: " + name + " | type: " + type);}}}}// 如果成员是函数定义,也可以在这里处理(可选)else if (member instanceof IASTFunctionDefinition) {IASTFunctionDefinition fd = (IASTFunctionDefinition) member;String fname = fd.getDeclarator() != null && fd.getDeclarator().getName() != null ?fd.getDeclarator().getName().toString() : "<anon>";System.out.println("  method-def: " + fname);}}}// 如果这是顶层 enum(也可能出现在类内)else if (declSpec instanceof ICPPASTEnumerationSpecifier) {// 可按需处理}}// 另外,如果遇到类外的函数定义(有函数体),也可以处理else if (declaration instanceof IASTFunctionDefinition) {// 处理类外限定名的函数定义(例如 CAbstractRead::serialize)IASTFunctionDefinition funcDef = (IASTFunctionDefinition) declaration;IASTFunctionDeclarator fd = funcDef.getDeclarator();if (fd != null) {System.out.println("Top-level function def: " + fd.getName());}}return PROCESS_CONTINUE;}});// 5. 从 binding 里提取字段for (IASTDeclaration decl : translationUnit.getDeclarations()) {if (decl instanceof IASTSimpleDeclaration) continue;if (decl instanceof ICPPASTCompositeTypeSpecifier) {ICPPASTCompositeTypeSpecifier cls = (ICPPASTCompositeTypeSpecifier) decl;ICPPClassType binding = (ICPPClassType) cls.getName().resolveBinding();if (binding != null) {System.out.println("类名: " + binding.getName());for (ICPPField field : binding.getDeclaredFields()) {System.out.println("成员变量: " + field.getName() +" , 类型: " + field.getType().toString());}}}}}private static void handleClassMember(IASTDeclaration member) {if (member instanceof IASTSimpleDeclaration) {IASTSimpleDeclaration memberDecl = (IASTSimpleDeclaration) member;IASTDeclarator[] declarators = memberDecl.getDeclarators();if (declarators.length == 0) return;// 变量if (!(declarators[0] instanceof IASTFunctionDeclarator)) {String type = memberDecl.getDeclSpecifier().getRawSignature();for (IASTDeclarator d : declarators) {String name = d.getName().toString();System.out.println("  字段: " + name + " | 类型: " + type);}}}}}

  

代码注意点: 

//上面代码中的这里可以把 c++里面的宏跳过定义处理,如果你的头文件有定义宏,并且没有在这put上,可能会解析失败
HashMap<String, String> macros = new HashMap<>();

  

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/918027.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Chormium 密码管理器表单结构体说明(基于Chromium138)

这个结构体(struct PasswordForm)是 Chromium 浏览器(以及所有基于 Chromium 的浏览器,例如 Chrome、Edge 等)中密码管理器用来存储和管理单个登录凭证(即一组用户名和密码)的核心数据结构。它不仅包含了用户名…

为什么人工智能选择Python?深入解析AI界的胶水语言

在人工智能(AI)的黄金时代,Python几乎"统治"了整个领域。从深度学习到机器学习,从学术研究到工业应用,Python无处不在。 但为什么是Python?为什么不是性能更强的C++、生态成熟的Java,或者其他现代语言…

惠安网站建设报价网站开发工程师招聘要求

有很多网友在问&#xff1a;TPlink路由器端口映射怎么设置&#xff1f;因为不懂端口映射的原理&#xff0c;所以无从下手&#xff0c;下面小编就给大家分享TPlink云路由器界面端口映射设置方法&#xff0c;帮助大家快速入门TP路由器端口映射设置方法。 1.登录路由器管理界面&a…

咸宁网站设计windows 上wordpress

上一篇中 我们详细讲了内存溢出 内存泄漏 还有相关的案例。 这篇博客中我们主要了解一下GC调优。 有些新手可能会有一点 疑问—— 这两者不是一回事吗&#xff1f;&#xff1f; 其实说一回事 也没错 因为GC调优本质上还是针对 堆上的内存 只不过前面我们关注的侧重点在于 不合…

模版网站有源代码吗注册公司代理费用多少钱

【vs2019】window10环境变量设置 【先赞后看养成习惯】求关注点赞收藏&#x1f60a; 安装VS2019时建议默认安装地址&#xff0c;最好不要改动&#xff0c;不然容易出问题 以下是安装完VS2019后环境变量的设置情况&#xff0c;C:\Program Files (x86)\Microsoft Visual Studi…

1 day(20250925) - when

第一天,好像时间还可利用的地方很多,其实是效率和时长都有待提升。 哇要做的事情都蛮复杂和多的,其实没那么难对吧,不过太多了,想要迈大步就变得不可能实现,而且迈大步总感觉会错过一些细节,不能够有底气。但是…

12分钟讲解Python核心理念

https://segmentfault.com/a/1190000047277781 12分钟讲解Python核心理念 本内容是对 Every Python Concept Explained in 12 Minutes 内容的翻译与整理。 Python之禅(The zen of Python) 当你在Python解释器中输入i…

【重要】什么是 PEP 8 规范

PEP 8 是 Python 官方的代码风格指南,全称为 Python Enhancement Proposal 8(Python 增强提案 8),旨在通过统一编码规范提升代码的可读性、一致性和可维护性。以下是其核心内容与重要性: 一、PEP 8 的核心规范代码…

实用指南:华为坤灵:点燃中小企业智能化的星火

实用指南:华为坤灵:点燃中小企业智能化的星火pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", &…

阻止HTML input元素(type=number)中输入字母e的方法

在HTML中,<input type=number> 元素允许用户输入一个数字,它可以包含正数、负数、整数、浮点数以及特殊字符,如 e表示科学计数法。然而,在某些情况下,你可能不希望允许用户输入字母 e。为了实现这一目标,可…

荣县规划和建设局网站如何建设企业网站

力扣138&#xff1a;随机链表的复制 题目描述&#xff1a; 给你一个长度为 n 的链表&#xff0c;每个节点包含一个额外增加的随机指针 random &#xff0c;该指针可以指向链表中的任何节点或空节点。 构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成&#xff…

网站开发课表查询吉安工商注册官方网站

简介&#xff1a; 智能的运维平台&#xff0c;帮助企业业务平稳、智能、高效地运行。 每一起严重事故背后&#xff0c;必然有29次轻微事故和300起未遂先兆以及1000起事故隐患。—— 海恩法则(Heinrich‘s Law) 随着云计算时代的到来&#xff0c;大量企业将自己的业务逐步迁移…

网站建设广西企业展厅建筑外观

自己总结的&#xff0c;给大家参考一下&#xff0c;

【Prompt学习技能树地图】利用GitHub-Prompt Engineering Guide进阶学习Prompt工程指南 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

没有服务器 怎么做网站机构改革 住房与城乡建设厅网站

1️⃣ Nikto漏洞扫描 Nikto是一个开源的Web扫描评估程序&#xff0c;它可以对目标Web服务器进行快速而全面的检查&#xff0c;以发现各种潜在的安全问题和漏洞。 &#x1f170;️ 如何使用 ❓ nikto -Display 1234ep -h [域名或IP地址] -o nikto.html # -h参数&#xff1a;指…

下载好模板该怎么做网站google优化推广

java生成指定范围的随机数 /*** 如何在程序中生成指定范围的随机数** 生成23-59之间的随机数*/ public class Test11 {public static void main(String[] args) {/*** Math.random() 生成&#xff08;0,1&#xff09;之间的小数&#xff0c;不包括0和1* 所以生成23-59之间的随…

深入解析:KRaft 运维从静态到动态 Controller

深入解析:KRaft 运维从静态到动态 Controllerpre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", &q…

Windows时间同步列表注册表授时时间服务器

前言全局说明Wnindows 时间同步列表添加删除一、说明 1.1 环境: Windows 7 旗舰版二、时间同步列表 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers三、授时时间服务器: 57种语言,…

常州网站建设要多少钱企业运营流程

本文将探讨嵌入式系统中的GPIO(通用输入输出)控制,着重介绍GPIO的原理和基本用法。我们将使用一个实际的示例项目来演示如何通过编程配置和控制GPIO引脚。将基于ARM Cortex-M微控制器,并使用C语言进行编写。 GPIO是嵌入式系统中最常见且功能最强大的接口之一。它允许硬件工…