是否可以在C ++的运行时动态创建一个函数? [英] Is it possible to create a function dynamically, during runtime in C++?

查看:1196
本文介绍了是否可以在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)


  1. 使用 ofstream
  2. 将C ++程序写入文件(例如在/tmp/prog.cc中) >
  3. 通过 system(c ++ /tmp/prog.cc -o /tmp/prog.so -shared -fPIC);

  4. 动态加载程序,例如使用 dlopen()

  1. write a C++ program into a file (e.g. in /tmp/prog.cc), using an ofstream
  2. compile the program via system("c++ /tmp/prog.cc -o /tmp/prog.so -shared -fPIC");
  3. load the program dynamically, e.g. using dlopen()

这篇关于是否可以在C ++的运行时动态创建一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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