Skip to content

Instantly share code, notes, and snippets.

@Moligaloo
Last active January 31, 2016 05:51
Show Gist options
  • Save Moligaloo/0f52be287d360159b43c to your computer and use it in GitHub Desktop.
Save Moligaloo/0f52be287d360159b43c to your computer and use it in GitHub Desktop.
Chain invocation in C programming language
#include <glib.h>
#include <stdlib.h>
#include <stdio.h>
// MyJIT homepage: http://myjit.sourceforge.net/index.htm
#include "myjit/jitlib.h"
struct string_builder{
GString *gstring;
struct string_builder * (*append)(const char *s);
const char *(*to_string)();
};
static struct string_builder *string_builder_append(struct string_builder *sb, const char *s){
sb->gstring = g_string_append(sb->gstring, s);
return sb;
}
static const char *string_builder_to_string(struct string_builder *sb){
return sb->gstring->str;
}
void bind_zero2one(void *ptr_to_func, void *call_func, void *self){
struct jit *p = jit_init();
jit_prolog(p, ptr_to_func);
jit_prepare(p);
jit_putargi(p, self);
jit_call(p, call_func);
jit_retval(p, R(0));
jit_retr(p, R(0));
jit_generate_code(p);
jit_free(p);
}
void bind_one2one(void *ptr_to_func, void *call_func, void *self){
struct jit *p = jit_init();
jit_prolog(p, ptr_to_func);
jit_declare_arg(p, JIT_PTR, sizeof(const char *));
jit_getarg(p, R(0), 0);
jit_prepare(p);
jit_putargi(p, self);
jit_putargr(p, R(0));
jit_call(p, call_func);
jit_retval(p, R(0));
jit_retr(p, R(0));
jit_generate_code(p);
}
struct string_builder *create_string_builder(){
struct string_builder *sb = g_new(struct string_builder, 1);
sb->gstring = g_string_new(NULL);
bind_one2one(&sb->append, string_builder_append, sb);
bind_zero2one(&sb->to_string, string_builder_to_string, sb);
return sb;
}
void string_builder_free(struct string_builder *sb){
g_free(sb->gstring);
g_free(sb);
}
int main(int argc, char const *argv[]) {
struct string_builder *sb = create_string_builder();
const char *result = sb
->append("hello\n")
->append("world\n")
->to_string();
printf("%s", result);
string_builder_free(sb);
return 0;
}
@fanfeilong
Copy link

不过,如果每个函数都这么写,太麻烦了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment