C/C++头文件解析(使用Eclipse插件CDT现有API)

C/C++头文件解析(使用Eclipse插件CDT现有API)

需求

解析C/C++头文件,展示出C/C++头文件中定义的头文件原型。一个现有的资源就是CDT自带的C/C++,如下图右边所示:
在这里插入图片描述
注意: 以上图中(CDT)是需要打开头文件的。我们需要在不打开头文件的情况下进行分析数据。
我不想自己造轮子,想通过CDT源码中现有API解决该问题。阅读到的相关类有:

  • CEditor
  • CContentOutlinePage
  • CDocumentProvider
  • IWorkingCopyManagerWorkingCopy
  • FunctionDeclaration

最终实现代码及数据展示

		FileEditorInput editorInput = WorkbenchUtil.getFileEditorInput(relativePath);
		// 获取C/C++头文件解析数据 ICElement[] ,源码中拼凑
		CDocumentProvider cdp = new CDocumentProvider();
		IWorkingCopyManager manager = new WorkingCopyManager(cdp);
		manager.connect(editorInput);
		WorkingCopy workingCopy = (WorkingCopy)manager.getWorkingCopy(editorInput);
		ICElement[] children = workingCopy.getChildren();
		if(Objects.isNull(children)) continue;
		for(ICElement cElement : children) {
			if(!(cElement instanceof FunctionDeclaration)) continue;
			if(Objects.isNull(cElement)) continue;
			FunctionDeclaration functionDeclaration = (FunctionDeclaration)cElement;
		}

测试

准备的头文件

在这里插入图片描述
math-01.h 头文件信息

#pragma once

int add(int a, int b);

debug 数据展示

Debug 调试结果:
在这里插入图片描述
Debug Shell 调试代码及输出:

	// 相对于eclipse 工作空间的文件路径
	relativePath
	 (java.lang.String) 函数库管理\sys\include\math-01.h
	 // 第一个函数数据
	 // 返回值
	functionDeclaration.getReturnType()
	 (java.lang.String) int
	 //参数类型列表
	functionDeclaration.getParameterTypes()
	 (java.lang.String[]) [int, int]
	 //函数名
	functionDeclaration.getElementName()
	 (java.lang.String) add
	 // 由以上数据可以拼接出函数原型
	 // int add(int,int);

其中 WorkbenchUtil 工具包中与 getFileEditorInput 相关代码如下

	/**
	 * 获取工作空间
	 * @return
	 */
	public static IWorkspace getWorkspace() {
		return ResourcesPlugin.getWorkspace();
	}
	
	/**
	 * 获取根工作空间
	 * @return
	 */
	public static IWorkspaceRoot getWorkspaceRoot() {
		return getWorkspace().getRoot();
	}

	/**
	 * 获取工作空间中的文件
	 * @param filePath
	 * @return
	 */
	public static IFile getWorkSpaceFile(String filePath) {
		return getWorkSpaceFile(new Path(filePath));
	}

	/**
	 * 获取工作空间中的文件
	 * @param filePath 文件路径
	 * @return
	 */
	public static IFile getWorkSpaceFile(IPath filePath) {
		return getWorkspaceRoot().getFile(filePath);
	}

	/**
	 * 获取文件编辑器输入文件
	 * @param fileName
	 * @return
	 */
	public static FileEditorInput getFileEditorInput(String fileName) {
		IFile file = getWorkSpaceFile(fileName);
		if (Objects.isNull(file) || !file.exists()) {
			return null;
		}
		String exString = file.getFileExtension();
		if (exString == null)
			return null;
		return new FileEditorInput(file);
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值