使用libclang,回调函数不递归遍历并且不访问所有函数
问题描述:
我正在遵循一个示例,它显示了Python绑定的限制,从站点http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang/ 它使用“libclang直接访问API”。使用libclang,回调函数不递归遍历并且不访问所有函数
import sys
import clang.cindex
def callexpr_visitor(node, parent, userdata):
if node.kind == clang.cindex.CursorKind.CALL_EXPR:
print 'Found %s [line=%s, col=%s]' % (
node.spelling, node.location.line, node.location.column)
return 2 # means continue visiting recursively
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
clang.cindex.Cursor_visit(
tu.cursor,
clang.cindex.Cursor_visit_callback(callexpr_visitor),
None)
输出显示所有调用的函数及其行号。
Found foo [line=8, col=5]
Found foo [line=10, col=9]
Found bar [line=15, col=5]
Found foo [line=16, col=9]
Found bar [line=17, col=9]
当我运行相同的代码,我只得到输出
Found bar [line=15, col=5]
我使用的版本是llvm3.1与Windows(与链接建议的修改)。
我觉得,返回2不会再次调用回调函数。 我甚至尝试过在节点上使用'get_children'并且在没有回调的情况下遍历,我得到了同样的结果。
import sys
import clang.cindex
#def callexpr_visitor(node, parent, userdata):
def callexpr_visitor(node):
if node.kind == clang.cindex.CursorKind.CALL_EXPR:
print 'Found %s [line=%s, col=%s]' % (
clang.cindex.Cursor_displayname(node), node.location.line, node.location.column)
for c in node.get_children():
callexpr_visitor(c)
#return 2 # means continue visiting recursively
index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
#clang.cindex.Cursor_visit(
# tu.cursor,
# clang.cindex.Cursor_visit_callback(callexpr_visitor),
# None)
callexpr_visitor(tu.cursor)
经过大量的搜索和试验,我无法得到这种行为的原因。 任何人都可以解释这个吗? 此致敬礼。
答
我想我找到了原因。
如果我更改函数'foo'的返回类型,从'bool'更改为'int',我会得到预期结果。
这可能是'bool'不是'c'中的关键字。 这很简单。