Hi guys,
I’m still dabbling with graphics, this time working on a fractal explorer and today, on a whim, I came up with this absurd alternative to using an array of function pointers:
Code:
// On a header file:
typedef struct s_fractal
{
...
...
unsigned int (*compute)(struct s_fractal *, t_i2dcoordinate, unsigned int);
...
...
} t_fractal;
//On the fractal calculator source file. Above header file is included for the t_fractal type.
static unsigned int compute_julia
(t_fractal *fractal, const t_i2dcoordinate screen_coordinates,
const unsigned int max_iterations)
{
...
...
return (iterations);
}
static const t_fractal_params parameters =
{
{
...
{&compute_julia, "julia", {-2.5, -1}, {1, 1}, {0.7, 0}, (-0.743643f + 0.131825f * I)},
...
}
};
extern void initialize_fractal(t_fractal *fractal, const char *fractal_name /*coming from argv*/)
{
...
while (strcmp(fractal_name, parameters.fractals[id].name))
++id;
...
(*fractal).compute = parameters.fractals[id].compute;
...
}
// Finally, on my rendering source file:
static void *resolve_fractal(void *thread)
{
t_workset *workset = (*(t_thread_data*)thread).workset;
t_fractal *fractal = (*workset).fractal;
...
...
iterations = (*fractal).compute(fractal, screen_coordinates);
(*workset).framebuffer[.....] = get_pixel_color(iterations);
...
...
pthread_exit((void*)0);
}
And it works!
I like it much better than my usual array of function pointers solution, because for one I don't have to deal with arrays and more importantly, using the "object.function" syntax seems neater to me.
Now, I have great uncertainty on whether this is dangerous, results in undefined behavior, is violating all the iso standards or can make my toaster explode.
resolve_fractal is a static function, and so not visible to the outside world. Yet I am using it in the ouside world, exclusively. Does the compiler generate symbols for this function? What if I declare it inline? (I tried and it works all the same). How would compiling with -flto change things?
I'd greatly appreciate your take on this?
Thank you.