Skip to content

Instantly share code, notes, and snippets.

@yangacer
Created January 2, 2014 02:56
Show Gist options
  • Save yangacer/8214314 to your computer and use it in GitHub Desktop.
Save yangacer/8214314 to your computer and use it in GitHub Desktop.
Member function with pure C
#include "impl.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct obj_impl
{
int a;
};
static void add_and_print(struct obj_impl *o, int val)
{
assert(o != 0 && "Invalid instance");
o->a += val;
printf("a = %d\n", o->a);
}
static void substract_and_print(struct obj_impl *o, int val)
{
assert(o != 0 && "Invalid instance");
o->a -= val;
printf("a = %d\n", o->a);
}
static fn_ptr_table_t mfn_table = {
.add_and_print = &add_and_print,
.substract_and_print = &substract_and_print
};
obj_t create_obj(int a)
{
obj_t wobj = {
.inst_ = malloc(sizeof(struct obj_impl)),
.fn_ptr_table_ = &mfn_table
};
wobj.inst_->a = a;
return wobj;
}
void destroy_obj(obj_t *obj)
{
free(obj->inst_);
obj->inst_ = 0;
}
#ifndef IMPL_H_
#define IMPL_H_
struct obj_impl;
typedef struct fn_ptr_table
{
void (*add_and_print)(struct obj_impl *, int);
void (*substract_and_print)(struct obj_impl*, int);
} fn_ptr_table_t;
typedef struct obj
{
fn_ptr_table_t const *fn_ptr_table_;
struct obj_impl *inst_;
} obj_t;
obj_t create_obj(int a);
void destroy_obj(obj_t *obj);
#endif
#include "impl.h"
#include <stdio.h>
#define call_mfn(Handle, Mfn, ...) \
Handle.fn_ptr_table_->Mfn(Handle.inst_, __VA_ARGS__)
int main()
{
obj_t wobj = create_obj(123);
printf("sizeof obj_t: %zu\n", sizeof(obj_t));
call_mfn(wobj, add_and_print, 456);
call_mfn(wobj, substract_and_print, 456);
destroy_obj(&wobj);
call_mfn(wobj, add_and_print, 455);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment