libclang获取原始值 [英] libclang get primitive value

查看:303
本文介绍了libclang获取原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用libclang获取原始文字的值?

How can I get the value of a primitive literal using libclang?

例如,如果我有一个游标类型为CXCursor_IntegerLiteral的CXCursor,那么如何提取文字值.

For example, if I have a CXCursor of cursor kind CXCursor_IntegerLiteral, how can I extract the literal value.

更新:

使用libclang遇到了很多问题.我强烈建议完全避免使用它,而应使用clang提供的C ++接口. C ++界面具有很高的可用性,并且有很好的文档记录: http://clang.llvm.org/doxygen/annotated.html

I've run into so many problems using libclang. I highly recommend avoiding it entirely and instead use the C++ interface clang provides. The C++ interface is highly useable and very well documented: http://clang.llvm.org/doxygen/annotated.html

我现在看到libclang的唯一目的是使用以下代码为您生成ASTUnit对象(否则这并不容易):

The only purpose I see of libclang now is to generate the ASTUnit object for you as with the following code (it's not exactly easy otherwise):

ASTUnit * astUnit;
{
    index = clang_createIndex(0, 0);
    tu = clang_parseTranslationUnit(
        index, 0,
        clangArgs, nClangArgs,
        0, 0, CXTranslationUnit_None
        );
    astUnit = static_cast<ASTUnit *>(tu->TUData);
}

现在您可能会说libclang是稳定的,而C ++接口不是.这几乎没有关系,因为您花费大量时间用libclang来确定AST并使用它来创建kludges会浪费您大量的时间.我会尽快花几个小时来修复在版本升级后无法编译的代码(如果需要的话).

Now you might say that libclang is stable and the C++ interface isn't. That hardly matters, as the time you spend figuring out the AST with libclang and creating kludges with it wastes so much of your time anyway. I'd just as soon spend a few hours fixing up code that does not compile after a version upgrade (if even needed).

推荐答案

在翻译单元中,您已经拥有所需的所有信息,而无需重新解析原始文件:

Instead of reparsing the original, you already have all the information you need inside the translation unit :

if (kind == CXCursor_IntegerLiteral)
{
    CXSourceRange range = clang_getCursorExtent(cursor);
    CXToken *tokens = 0;
    unsigned int nTokens = 0;
    clang_tokenize(tu, range, &tokens, &nTokens);
    for (unsigned int i = 0; i < nTokens; i++)
    {
        CXString spelling = clang_getTokenSpelling(tu, tokens[i]);
        printf("token = %s\n", clang_getCString(spelling));
        clang_disposeString(spelling);
    }
    clang_disposeTokens(tu, tokens, nTokens);
}

您将看到第一个标记是整数本身,下一个则不相关(例如,对于int i = 42;,它是;.

You will see that the first token is the integer itself, the next one is not relevant (eg. it's ; for int i = 42;.

这篇关于libclang获取原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆