【发布时间】:2012-10-25 13:09:18
【问题描述】:
我正在编写一个简单的工具来帮助重构我们应用程序的源代码。我想解析基于 wxWidgets 库的 C++ 代码,该库定义 GUI 并生成 XML .ui 文件以与 Qt 一起使用。我需要获取所有函数调用和参数值。
目前我正在玩弄 Python 到 Clang 的绑定,使用下面的示例代码我得到了标记及其种类和位置,但光标种类始终是 CursorKind.INVALID_FILE。
import sys
import clang.cindex
def find_typerefs(node):
""" Find all references to the type named 'typename'
"""
for t in node.get_tokens():
if not node.location.file != sys.argv[1]:
continue
if t.kind.value != 0 and t.kind.value != 1 and t.kind.value != 4:
print t.spelling
print t.location
print t.cursor.kind
print t.kind
print "\n"
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
print 'Translation unit:', tu.spelling
find_typerefs(tu.cursor)
确定光标种类的正确方法是什么?
除了几篇博客文章外,我找不到任何文档,但它们已经过时或没有涵盖这个主题。我也无法从 Clang 附带的示例中解决它。
【问题讨论】:
-
你能给出
list(f.source.name for f in tu.get_includes())的输出吗? (只需在脚本末尾打印) -
和其他c编译器一样,include文件夹也要正确设置,index.parse(sys.argv[1],args=['I./path/to/include', ' I./another/include'])
-
代替别人的工作并不丢人,只是别忘了提一下:您的代码在某种程度上与 Eli 页面中的第一个示例非常相似:eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang