Tricking C: Function pointers in C structs
Software
So today in the l2l the question came up, "Can you use function pointers in C structs to get around the 'no functions in structs' thing." So like any good scientist I opened up vim and typed up a test:
#include <stdio.h>
int Foo_square(int a);
struct Foo {
int (*square)(int);
};
int main()
{
struct Foo bar;
bar.square = &Foo_square;
printf("%dn", bar.square(4));
return 0;
}
int Foo_square(int a)
{
return a * a;
}
So, it works just fine. Now I decided to see about making it less messy like you would have with an object oriented language. I broke the file into a header file and source code file. *note* It has been brought up that I should have done the following header file in the more traditional .h is an interface with a .c file implementing the various functions. While it is tradition, I believe that it is extraneous for what I am trying to show here.
Header:
#ifndef FILE_H
#define FILE_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
void (*open_write)();
void (*open_read)();
void (*set_filename)(char*);
FILE* fp;
char file_name[100];
} File;
File* new_File();
File* this;
void File_open_write()
{
this->fp = fopen(this->file_name,"w");
}
void File_open_read()
{
this->fp = fopen(this->file_name,"r");
}
void File_set_filename(char* file_name)
{
strncpy(this->file_name,file_name,99);
}
File* new_File()
{
this = (File*)malloc(sizeof(File));
this->open_write = &File_open_write;
this->open_read = &File_open_read;
this->set_filename = &File_set_filename;
memset(this->file_name,(int)NULL,100);
return this;
}
#endif
Source File:
#include "File.h"
#include <stdio.h>
int main()
{
File* bar = new_File();
bar->set_filename("test.txt");
printf("%sn", bar->file_name);
return 0;
}
The header file simply defines everything that will be needed for the File struct along with a fuction new_File() which creates a pointer for the struct, sets up the functions and returns the pointer. This makes the source file extremely clean, because all you do is call new_File() and everything is done. You can now manipulate the struct similarly to how you would manipulate an object. This actually looks a lot like how php classes work... god dammit...
Created: 2009-04-05 23:52:05

