使用clang API编译和运行C代码 [英] Compile and run C code using clang API

查看:36
本文介绍了使用clang API编译和运行C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用clang/llvmAPI编译一个在字符串中定义的c函数,并立即执行它。 类似于:

void main() {
  std::string codestr = "int foo(int bar) { return bar * 2; }"

  clang::??? *code = clang::???.compile(codestr);

  int result = code->call("foo", 5);
}

我正在寻找教程,但到目前为止我发现的不太符合我的目标或不起作用,因为它引用的是过时版本的LLVM。 我当前使用的是LLVM 3.5。

有人手头有好的教程吗?

推荐答案

我关注了this blog post,效果不错。clang API已更改,因此您可能需要进行调整。对于LLVM 3.6.1,我使用以下代码获得了很好的结果:

llvm::Module* compile(const char* filename) {                                                   
        clang::CompilerInstance compiler;                                                     
        clang::CompilerInvocation* invocation = new clang::CompilerInvocation();              
        llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID(new clang::DiagnosticIDs());    
        auto diagOptions = new clang::DiagnosticOptions();                                    
        clang::DiagnosticsEngine Diags(DiagID, diagOptions,                                   
                new clang::TextDiagnosticPrinter(llvm::errs(), diagOptions));                 
        std::vector<const char *> arguments = {filename};            
        clang::CompilerInvocation::CreateFromArgs(*invocation,                                
                &*arguments.begin(), &*arguments.end(),                                       
                Diags);                                                                       
        compiler.setInvocation(invocation);                                                   
        compiler.setDiagnostics(new clang::DiagnosticsEngine(DiagID, diagOptions,                                   
                new clang::TextDiagnosticPrinter(llvm::errs(), diagOptions)));                                                      
        std::unique_ptr<clang::CodeGenAction> action(new clang::EmitLLVMOnlyAction());        
        compiler.ExecuteAction(*action);                                                      
        std::unique_ptr<llvm::Module> result = action->takeModule();                          
        llvm::errs() << *result;                                                              
        return result.release();                                                              
}                                                                                             

我对指针非常粗心,所以很可能是内存泄漏或双重释放(尽管它没有崩溃)。

我不知道如何从内存缓冲区获取源,所以使用mkstemp将其转储到临时文件中。

我没有执行结果,但我认为您可以关注@Michael-Haidi的回答,或查看LLVM万花筒教程(This is the JIT chapter)。

这篇关于使用clang API编译和运行C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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