【问题标题】:using libclang, callback function does not traverse recursively and does not visit all functions使用libclang,回调函数不会递归遍历,不会访问所有函数
【发布时间】:2013-11-27 16:18:28
【问题描述】:

我正在关注一个显示 python 绑定限制的示例,来自站点 http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang/ 它直接使用“libclang 访问 API”。

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]

我使用的版本是带有 windows 的 llvm3.1(链接中建议的更改)。

我感觉,返回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)

经过多次搜索和试验,我无法找到这种行为的原因。 谁能解释一下? 问候。

【问题讨论】:

    标签: python callback function-calls libclang


    【解决方案1】:

    我想我找到了原因。

    如果我将函数 'foo' 的返回类型从 'bool' 更改为 'int',我会得到预期的结果。

    这可能是因为 'bool' 不是 'c' 中的关键字。 这很简单。

    【讨论】:

      猜你喜欢
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2021-10-03
      • 2023-03-24
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多