関数型C言語
Cを関数型のように使いたい。
#include <stdio.h> #include <stdlib.h> #include <string.h> int (*flip(int (*fun)(int,int)))(int,int) { unsigned char *func = (char*)malloc(1000); func[ 0]=0x8B;func[ 1]=0x44;func[ 2]=0x24;func[ 3]=0x04; func[ 4]=0x87;func[ 5]=0x44;func[ 6]=0x24;func[ 7]=0x08; func[ 8]=0x89;func[ 9]=0x44;func[10]=0x24;func[11]=0x04; func[12]=0xB8;*(int**)(func+13)=(int*)fun; func[17]=0xFF;func[18]=0xE0; return (int(*)(int,int))func; } int mult(int x,int y) { return (x+1)*y; } int main() { printf("%d:%d\n",mult(5,4),flip(mult)(5,4)); }
のでとりあえず、flipを組んでみました。x86 専用。
windowsXP : "cygwin gcc" "VC++6.0" "Borland C++5.5.1"
Gentoo Linux : "gcc 3.3.4"
で動作確認しましたとさ。
SとKを組みたいのだけれども malloc をどうするかが思案どころ。