Artem Selivanov
Artem Selivanov

Reputation: 1957

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

Are have you any idea to do it? I'm not familar with any code parsers, but I know with clang is feasible.

The code I want to parse:

// 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;
};

Look at macros like a UCLASS and UFUNCTION. The using this macros may be entails wrong parsing. But I need to get all functions decorated by UFUNCTION macro (function names and arguments).

My useless code (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)

I removed UCLASS() and FLYING_API macros due to wrong parsing. The code below to avoid this not helps:

#define UCLASS(...)
#define FLYING_API

Output of python code:

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

Upvotes: 2

Views: 2013

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69902

I did a quick google search for "libclang parse c++".

One interesting link it came up with was this:

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

Which ought to give you enough information to do what you want.

Sorry I can't post code myself - I've never needed to do this.

Upvotes: 3

Related Questions