是否可以在 C++ 运行时动态创建函数?
C++ 是一种静态的编译语言,模板在编译时解析等等...
C++ is a static, compiled language, templates are resolved during compile time and so on...
但是是否可以在运行时创建一个函数,在源代码中没有描述,在编译过程中也没有转换成机器语言,这样用户就可以向它抛出源中没有预料到的数据?
But is it possible to create a function during runtime, that is not described in the source code and has not been converted to machine language during compilation, so that a user can throw at it data that has not been anticipated in the source?
我知道这不可能以一种直接的方式发生,但肯定是有可能的,有很多编程语言没有被编译,而是动态地创建了用 C 或 C++ 实现的那种东西.
I am aware this cannot happen in a straightforward way, but surely it must be possible, there are plenty of programing languages that are not compiled and create that sort of stuff dynamically that are implemented in either C or C++.
也许如果为所有原始类型创建工厂,以及将它们组织成更复杂的对象(例如用户类型和函数)的合适的数据结构,这是可以实现的吗?
Maybe if factories for all primitive types are created, along with suitable data structures to organize them into more complex objects such as user types and functions, this is achievable?
欢迎提供有关该主题的任何信息以及指向在线材料的提示.谢谢!
Any info on the subject as well as pointers to online materials are welcome. Thanks!
我知道这是可能的,更像是我对实现细节感兴趣:)
I am aware it is possible, it is more like I am interested in implementation details :)
推荐答案
是,当然,没有任何工具在其他答案中提到,但只是使用 C++ 编译器.
Yes, of course, without any tools mentioned in the other answers, but simply using the C++ compiler.
只需在您的 C++ 程序中执行这些步骤(在 linux 上,但在其他操作系统上必须类似)
just follow these steps from within your C++ program (on linux, but must be similar on other OS)
- 使用
ofstream
将 C++ 程序写入文件(例如在/tmp/prog.cc 中) - 通过
system("c++/tmp/prog.cc -o/tmp/prog.so -shared -fPIC");
编译程序 - 动态加载程序,例如使用
dlopen()
相关文章