C語言里如何按需生成函數指針數組?

比如Python里可以寫(大致是這樣的)

&>&>&> funlist=[]

&>&>&> def foo(x):

... return lambda k:k+x

...

&>&>&> for i in range(10):

... funlist.append(foo(i))

...

&>&>&> funlist[5](8)

13

或者像mathematica裡面的

a[i_] := # + i ; Table[a[i], {i, 1, 8}]

如果選用允許嵌套函數定義的c的標準,能實現類似功能嗎?(剛才舉的兩個例子似乎都是在搞匿名函數。。。)


C++ 怎麼生成 4096 個函數?

參考這裡的宏,編譯時生成這些函數是可行的。

C++ 的話用 index_sequence 模板就行。


換C++輕鬆做到:

vector&&> funlist;
for(int i = 0; i &< 10; i++) funlist.push_back([=](int j){return i+j;}); cout &<&< funlist[5](8) &<&< endl;

如果一定要函數指針的話,在使用VC++x86的前提下,可以用我上大學的時候胡寫的一段代碼(【源碼下載】JIT腳本引擎:CMinus 0.1版開放下載 - λ-calculus(驚愕到手了歐耶,GetBlogPostIds.aspx) - C++博客)

typedef int(__stdcall*Adder)(int);
Adder funlist[10];
VL_CMinusExecutable::Ptr executables[10];
for(int i=0;i&<10;i++) { VUnicodeString code = L"int fuck(int x)" L"{" L" return x + " + itow(i) + L";" L"}"; VL_CMinusError error; VL_ListedMap& externals;
auto program = CompileToCMinusProgram(code, error);
auto executable = program-&>Compile(error, externals);
auto fuck = reinterpret_cast&(executable-&>GetEntry(L"fuck"));
funlist[i] = fuck;
executables[i] = executable;
}


你的意思是函數指針記錄某個參數嗎?

int foo(int x,int y)

{

return x+y;

}

int param[10];

int (*pfun)(int x,y)=foo;

(*pfun)(param[5],8);

簡單的事情為啥搞這麼複雜呢


typedef struct Foo Foo;
struct Foo {
int x;
int (*foo)(Foo *self, int k);
};

Foo foo(int x, int (*func)(Foo *, int))
{
Foo self = {x, func};
return self;
}

int call(Foo *self, int k)
{
return self-&>foo(self, k);
}

int my_foo(Foo *self, int k)
{
return k + self-&>x;
}

int main(void)
{
Foo funlist[10];
for (int i = 0; i &< 10; i++) { funlist[i] = foo(i, my_foo); } printf("%d ", call(funlist[5], 8)); return 0; }


gcc下:

#include &
/*
* When use LAMBDA macro, arg_list should wrap with (),
* func_body should wrap with {}.
*/
#define LAMBDA(ret_type, arg_list, func_body) ({
ret_type fn arg_list
func_body
fn;
})

int main(int argc, char *argv[])
{
int (*func)(int,int) = LAMBDA(int, (int i, int j), {return i + j;});
int array[10];
int i;

for (i = 0; i &< 10; ++i) array[i] = i; printf("%d ", func(array[5], 8)); return 0; }

湊合著用吧。。。


放棄吧,我曾經腦子發熱給 C 寫過二進位層面的閉包函數 github.com/yulon/clofn ,最後還是老老實實用 C++ 了(掩面逃

C 裡面最貼近的實現應該是用個結構記錄數據,做成該結構的數組,執行函數的時候把結構作為參數傳進去(其實其他語言也大抵如此,只是語法糖的咸甜區別了


手機回答…

我是這麼做的…shellcode + 彙編引擎 + mmap/VirtulAlloc

是不太安全

我一個寫殼的管他安不安全


實現你這個例子的要素:

柯理化c原生不支持,因為c原生不支持動態生成函數,歸根到底是c語言是靜態語言沒有動態生成代碼的能力。

c++可以用lamada或者函數對象來實現。實際上本質上得益於operator ()操作,用對象模擬了函數的行為。


推薦閱讀:

sizeof(void*)的大小到底由何決定?
C++new運算符調用operator new 分配內存後, 構造函數調用及指針類型的轉換在哪裡完成?
有哪些較好的 C 語言程序源碼可供新手臨摹參考?
新手入門c語言應該下載那個軟體?

TAG:C編程語言 | Python編程 |