使用Python绑定到CLAN,以检查C++类型是否是规范的指针、引用等?

2024-10-03 02:40:26 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑类型^ {< CD1>}类型^ {CD2>},表示C++变量声明,如^ {CD3>}或发生在类似

的参数声明
template<typename... Ts> void f(Ts&&...);

有没有一种规范的方法来确定t是/代表(1)指针,(2)左值或右值引用,(3)参数包吗?在

显然,通过手动解析t.spelling,可以解决上述问题,大致如下:假设文件x.h包含

^{pr2}$

然后将打印True

import clang                                                                                          
from clang import cindex                                                                              

def is_lvalue_ref(type):                                                                              
    spell = type.spelling  # 'const T &'                                                              
    tokens = spell.split(' ')  # ['const', 'T', '&']                                                  
    return (tokens[-1] == '&')                                                                        

cindex.Config.set_library_path('/Library/Developer/CommandLineTools/usr/lib')                         
index = cindex.Index.create()                                                                         
tu = index.parse('x.h', ['c++', '-std=c++17'])                                                        
for x in tu.cursor.get_children():                                                                    
    # x is CursorKind.VAR_DECL                                                                        
    print(is_lvalue_ref(x.type))    

(对于指针或参数包,执行类似操作。)

但显然,这是不可取的!有没有一种规范的方法来实现这一点?在


Tags: 方法import规范ref声明类型参数is