Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用libclang检索完全限定的函数名?_Python_C++_Libclang - Fatal编程技术网

Python 如何使用libclang检索完全限定的函数名?

Python 如何使用libclang检索完全限定的函数名?,python,c++,libclang,Python,C++,Libclang,我需要解析C++代码文件,并找到它中的所有函数调用,并使用完全限定的名称。我使用的是LiBrangon的Python绑定,因为它比编写自己的C++解析器更容易,即使文档是稀疏的。 C++代码: namespace a { namespace b { class Thing { public: Thing(); void DoSomething(); int DoAnotherThing(); private: int

我需要解析C++代码文件,并找到它中的所有函数调用,并使用完全限定的名称。我使用的是LiBrangon的Python绑定,因为它比编写自己的C++解析器更容易,即使文档是稀疏的。 C++代码:

namespace a {
  namespace b {
    class Thing {
    public:
      Thing();
      void DoSomething();
      int DoAnotherThing();
    private:
      int thisThing;
    };
  }
}

int main()
{
  a::b::Thing *thing = new a::b::Thing();
  thing->DoSomething();
  return 0;
}
Python脚本:

import clang.cindex
import sys

def find_function_calls(node):
  if node.kind == clang.cindex.CursorKind.CALL_EXPR:
    # What do I do here?
    pass
  for child in node.get_children():
    find_function_calls(child)

index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
find_function_calls(tu.cursor)
我要查找的输出是被调用函数的完全限定名列表:

a::b::Thing::Thing
a::b::Thing::DoSomething
a::b::Thing::Thing
a::b::Thing::DoSomething

我可以通过使用
节点来获取函数的“short”名称。拼写
,但我不知道如何找到它所属的类/命名空间。

您可以使用cursor
referenced
属性来获取定义的句柄,然后可以通过
semantic\u parent
属性递归AST(在根目录处或光标类型为translation unit时停止)以构建完全限定名称

import clang.cindex
from clang.cindex import CursorKind

def fully_qualified(c):
    if c is None:
        return ''
    elif c.kind == CursorKind.TRANSLATION_UNIT:
        return ''
    else:
        res = fully_qualified(c.semantic_parent)
        if res != '':
            return res + '::' + c.spelling
    return c.spelling

idx = clang.cindex.Index.create()
tu = idx.parse('tmp.cpp', args='-xc++ --std=c++11'.split())
for c in tu.cursor.walk_preorder():
    if c.kind == CursorKind.CALL_EXPR:
        print fully_qualified(c.referenced)
产生: