Is it possible to create a function dynamically, during runtime in C++?(是否可以在 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()
这篇关于是否可以在 C++ 运行时动态创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 C++ 运行时动态创建函数?


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01