如何使用 python 和 clang 绑定获取 C++ header 中的方法列表?

How to get list of methods in C++ header using python with clang binding?

你有什么想法吗?我不熟悉任何代码解析器,但我知道用 clang 是可行的。

我要解析的代码:

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "InventoryItem.h"
#include "ItemView.h"
#include "InventoryScreen.generated.h"

class UGUIBase;

DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FInventoryScreenEvent, UInventoryItem*, item);

UCLASS()
class FLYING_API UInventoryScreen : public UGUIBase
{
    GENERATED_BODY()

public:
    virtual void NativeConstruct() override;
    virtual TSharedRef<SWidget> RebuildWidget() override;

public:
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Update event")
    void UpdateItemView(const TArray<UInventoryItem*>& Items);
    virtual void UpdateItemView_Implementation(const TArray<UInventoryItem*>& Items);

    UFUNCTION()
    void OnItemClicked(UInventoryItem* item);

    UPROPERTY(BlueprintAssignable, Category = "Button|Event")
    FInventoryScreenEvent OnClickedBy;

public:
    TWeakObjectPtr<UItemView> ItemView;
};

查看像 UCLASS 和 UFUNCTION 这样的宏。使用此宏可能会导致错误的解析。但我需要获取所有由 UFUNCTION 宏装饰的函数(函数名称和参数)。

我的无用代码(Python):

import clang.cindex

def look_header(node):

    print([c.displayname for c in node.get_children()])  #  Here I got 'DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam()', 'UGUIBase', 'UInventoryScreen', 'UGUIBase'

    for c in node.get_children():
        if c.displayname == "UInventoryScreen":  # I want to get all children of this class (all functions)
            print(list(c.get_children()))  # What subitems in this class? I got empty list (no anything)
            for cc in c.get_children():
                print(cc.displayname)

index = clang.cindex.Index.create()
tu = index.parse('InventoryScreen.h')
print('Translation unit:', tu.spelling)
look_header(tu.cursor)

由于解析错误,我删除了 UCLASS() 和 FLYING_API 宏。下面的代码避免这种情况没有帮助:

#define UCLASS(...)
#define FLYING_API

python 代码的输出:

Translation unit: InventoryScreen.h
['DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam()', 'UGUIBase', 'UInventoryScreen', 'UGUIBase']
[]
[]
[]
[]
[]

我快速 google 搜索了 "libclang parse c++"。

它提出的一个有趣的 link 是这样的:

http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang

这应该会给你足够的信息来做你想做的事。

抱歉,我不会 post 自己编写代码 - 我从来不需要这样做。