如何在运行时编译C ++代码(如Python中的eval)? [英] How to compile c++ code at runtime (like eval in Python)?

查看:151
本文介绍了如何在运行时编译C ++代码(如Python中的eval)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行时编译一些C ++代码,然后在某种插件系统中调用它们,另请参阅我的

I'm compiling some C++ code at runtime, which I'm then calling in a sort of plugin system, see also my other question. What I do is I create the source code, write it to a file, compile that file and write the output to another file. However, this process feels kinda ugly so I was hoping for some input.

//Open a file
std::ofstream fout("SOURCECODEPATH");

//Write actual function to file
fout << "extern \"C\" void testFunc(float testArray[]) {\n"
        "    testArray[0] = 1.0;\n"
        "    testArray[1] = 2.0;\n"
        "    testArray[2] = 3.0;\n"
        "}" << std::endl;

//Compile the file, and write the stdout and stderr to PROCESSOUTPUTPATH using "&>"
system("c++ -shared -fPIC -std=c++14 SOURCECODEPATH -o COMPILEDLIBRARYPATH &> PROCESSOUTPUTPATH");

//Read PROCESSOUTPUTPATH (not implemented)

当前它正在创建3个文件, SOURCECODEPATH COMPILEDLIBRARYPATH PROCESSOUTPUTPATH .但是,我宁愿没有将 SOURCECODEPATH PROCESSOUTPUTPATH 写入操作系统,而是在内部使用它们.因此,将源代码通过管道传递给进程并返回输出(最好拆分为stderr和stdout).最简单的方法是什么?

Currently it's creating 3 files, SOURCECODEPATH, COMPILEDLIBRARYPATH, and PROCESSOUTPUTPATH. However, I would much rather not have the SOURCECODEPATH and PROCESSOUTPUTPATH written to the OS, but rather have them used internally. So pipe (?) the sourcecode to the process and get back the output (preferable split into stderr and stdout). What would be the easiest way to do this?

推荐答案

请重新考虑您在做什么. C ++和Python在许多方面都是非常不同的语言,尤其是在它们的构建和执行模型中.看来非常不太可能运行时编译是解决您的根本问题(您尚未与我们共享)的真正解决方案.简而言之,C ++并非旨在支持此功能,Python则被设计为支持这种功能.

Please reconsider what you're doing. C++ and Python are very different languages in very many ways, not least in their build and execution models. It seems very unlikely that runtime compilation is the real solution to your underlying problem (which you have not shared with us). Simply put, C++ was not designed to support this, Python was.

从技术上讲,有一些C ++运行时编译的解决方案,但它们需要很多比Python中的eval更多的管理和工作量.但是,它们非常专业,因此再次不可能很好地解决您的基本问题.

Technically, there are a few solutions for runtime compilation of C++, but they require much more management and effort than eval in Python. However, they are pretty specialised and, again, unlikely to be a good solution to your underlying problem.

这篇关于如何在运行时编译C ++代码(如Python中的eval)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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