用C动态创建函数 [英] Dynamically creating functions in C

查看:85
本文介绍了用C动态创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何动态地用C编写一个函数?

How can I dynamically create a function in C?

我试着总结一下我的C的问题如下:

I try to summarize my C problem as follows:


  • 我有一个矩阵,我希望能够使用一些函数生成的元素。

  • I have a matrix and I want to be able to use some function to generate its elements.

函数没有参数

因此​​,我定义了以下内容:

Hence I define the following:

typedef double(function)(unsigned int,unsigned int);

/* writes f(x,y) to each element x,y of the matrix*/
void apply(double ** matrix, function * f);

现在我需要生成code范围内恒定的功能。我想到了创建一个嵌套函数并返回它的指针,但GCC手册(允许嵌套函数)说:

Now I need to generate constant functions within the code. I thought about creating a nested function and returning its pointer, but GCC manual (which allows nested functions) says:

如果你试图通过后,其地址调用函数的嵌套
  包含函数已经退出,所有的地狱将挣脱。

"If you try to call the nested function through its address after the containing function has exited, all hell will break loose."

我会有种从这个code期待...

which I would kind of expect from this code...

function * createConstantFunction(const double value){
 double function(unsigned int,unsigned int){
   return value;
 }
 return &function;
}

所以,我怎样才能得到它的工作?

So how can I get it to work?

谢谢!

推荐答案

C是编译语言。你不能在中C运行时创建code;有没有具体的支持C发出指令,内存等。当然,你可以尝试只分配内存,并确保它的可执行文件,并放出原机code那里。然后用合适的函数指针从C调用它。

C is a compiled language. You can't create code at run-time "in C"; there is no specific C support to emit instructions to memory and so on. You can of course try just allocating memory, making sure it's executable, and emit raw machine code there. Then call it from C using a suitable function pointer.

您不会得到从语言本身虽然任何帮助,这就像生成code和调用它在BASIC老8位机上。

You won't get any help from the language itself though, this is just like generating code and calling it in BASIC on an old 8-bit machine.

这篇关于用C动态创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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