如何使用带有clang绑定的python获取C ++头文件中的方法列表?

时间:2015-12-18 08:31:50

标签: python c++ parsing macros clang

您有什么想法吗?我不熟悉任何代码解析器,但我知道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']
[]
[]
[]
[]
[]

1 个答案:

答案 0 :(得分:1)

我快速搜索了“libclang parse c ++”。

它提出的一个有趣的链接是:

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

哪个应该给你足够的信息来做你想做的事。

抱歉,我不能自己发布代码 - 我从来不需要这样做。