• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
DeafManNoEars

Event Handlers In C

7 posts in this topic

I must admit that C is not my most fluent programming language.  I am trying to develop an event handling construct and just wanted to see if I was going down the proper path or if there are other more succinct options out there already.

 

Currently, I don't do anything special just print out a string when the event is raised.  It all seems to be working just fine; but again, I am not too comfortable with C so I'd like to know if there are things I am not doing the way I should be in C.

 

Please do point out any coding no-nos and the like as this is more an exercize to better my C skills.  It is not complete... for instance I still need to implement a remove handler function...just didn't want to put too much effort down this path if there are better ways to handle such.

#include <stdio.h>

#define MAX_NAME_LENGTH 10

/********************************************************************
	STRUCTURES AND ENUMS FOR
	EVENT HANDLING FUNCTIONS
********************************************************************/
typedef enum Events{
	TEST1,
	TEST2,
	TEST3,
	MAX_EVENTS
}e_Events;

typedef void (*callback) (void *);

typedef struct EventHandlers{
	callback cb;
	struct EventHandlers *next;
	char name[MAX_NAME_LENGTH];
} s_EventHandlers;

s_EventHandlers *listeners[MAX_EVENTS];

/********************************************************************
	FORWARD DECLARES FOR
	EVENT HANDLING FUNCTIONS
********************************************************************/
void InitListeners(s_EventHandlers *handlers[], int size);
void DestroyListeners(s_EventHandlers *handlers[], int size);
void RegisterEvent(e_Events event, callback cb, char *name);

/********************************************************************
	TEST EVENT HANDLERS FUNCTIONS
********************************************************************/
void Test1Handler1(void *data){
	printf("In Test1 Handler 1 %s\n", data);
}
void Test1Handler2(void *data){
	printf("In Test1 Handler 2 %s\n", data);
}
void Test2Handler1(void *data){
	printf("In Test2 Handler 1 %s\n", data);
}
void Test3Handler1(void *data){
	printf("In Test3 Handler 1 %s\n", data);
}
void Test3Handler2(void *data){
	printf("In Test3 Handler 2 %s\n", data);
}

int main(int argc, char **argv) 
{
	s_EventHandlers *handlers = NULL;
	char data[] = "this is the data";
	
	InitListeners(listeners,MAX_EVENTS);
	
	RegisterEvent(TEST1, Test1Handler1, "T1H1");
	RegisterEvent(TEST1, Test1Handler2, "T1H2");
	RegisterEvent(TEST2, Test2Handler1, "T2H1");
	RegisterEvent(TEST3, Test3Handler1, "T3H1");
	RegisterEvent(TEST3, Test3Handler2, "T3H2");
	
	handlers = listeners[TEST1];
	for(; handlers != NULL; handlers = handlers->next){
		handlers->cb(data);
	}
	
	handlers = listeners[TEST2];
	for(; handlers != NULL; handlers = handlers->next){
		handlers->cb(data);
	}
	
	handlers = listeners[TEST3];
	for(; handlers != NULL; handlers = handlers->next){
		handlers->cb(data);
	}
	
	DestroyListeners(listeners,MAX_EVENTS);
	
	return 0;
}

void RegisterEvent(e_Events event, callback cb, char *name){
	s_EventHandlers **handlers = &listeners[event];
	
	if (*handlers == NULL){
		*handlers = (s_EventHandlers*) malloc(sizeof s_EventHandlers);
		(*handlers)->cb = cb;
		
		strncpy((*handlers)->name,name,MAX_NAME_LENGTH);
		(*handlers)->name[MAX_NAME_LENGTH-1] = '\0';
		
		(*handlers)->next = NULL;
	} else { 
		while ((*handlers)->next != NULL){
			(*handlers)++;
		}
		(*handlers)->next = (s_EventHandlers*) malloc(sizeof s_EventHandlers);
		(*handlers)->next->cb = cb;
		
		strncpy((*handlers)->next->name,name,MAX_NAME_LENGTH);
		(*handlers)->next->name[MAX_NAME_LENGTH-1] = '\0';
		
		(*handlers)->next->next = NULL;
	}	
}

void InitListeners(s_EventHandlers *handlers[], int size){
	int i;
	for (i = 0; i < MAX_EVENTS; i++){
		handlers[i] = NULL;
	}
}

void DestroyListeners(s_EventHandlers *handlers[], int size){
	int i;
	s_EventHandlers *deleteMe, *next;
	for (i = 0; i < MAX_EVENTS; i++){
		deleteMe = handlers[i];
		
		while (deleteMe){
			next = deleteMe->next;
			free(deleteMe);
			deleteMe = next;
		}
	}
}
Edited by DeafManNoEars
0

Share this post


Link to post
Share on other sites

I would omit the name field for the event listeners. The only reason I can think that you'd want to have names attached to your event callbacks is so that you can identify them later for removal or to ensure that the same callback isn't registered for the same event more than once. Since this is C it's easy enough just to use the callback's address as the identifier. This will save some space in each callback, as well as spare you from having to work with strings (which in C, sucks pretty hard).

1

Share this post


Link to post
Share on other sites

Thanks smr.  I had really only put the names in the structs to print out some debug info, which I later removed but didn't remove from the struct.  I will certainly do that.

 

I hadn't even thought of the handling the possibility of attaching the same handler to the same event twice.  I will certainly look out for that.

 

And for that reason, my friend, I have +1'd that post. 

 

Other than that, and the fact that I am not returning errors from any of the functions are there any fundamental issues with the code?

 

I feel like there must be a better way to handle this case.

 

the (*handlers)->next->cb seems bulky to me.  And there must be a better option for this.

while ((*handlers)->next != NULL){
	(*handlers)++;
}
(*handlers)->next = (s_EventHandlers*) malloc(sizeof s_EventHandlers);
(*handlers)->next->cb = cb;
		
strncpy((*handlers)->next->name,name,MAX_NAME_LENGTH);
(*handlers)->next->name[MAX_NAME_LENGTH-1] = '\0';
		
(*handlers)->next->next = NULL;
Edited by DeafManNoEars
0

Share this post


Link to post
Share on other sites

What if malloc returns NULL (well, it'll crash).

 

Why are you traversing the entire list and placing the new handler at the end? Replace the head of the list with the new handler and point the next pointer at the old head. If you must place it at the end (i.e. you must call handlers in first added = first called order), use a doubly linked list instead and point the new handlers prev pointer at the old tail. (This is minor if you aren't expecting many handlers though, but is good practice if you must use a list).

 

If (*handlers)->next->cb seems bulky use a local variable to hold (*handlers)->next and dereference that from then on.

Edited by Paradigm Shifter
1

Share this post


Link to post
Share on other sites


Why are you traversing the entire list and placing the new handler at the end?

 

I like the idea of not having to traverse the entire list, though I just convinced myself that I'd like to check and ensure that the the same handler is not attached to the same event twice.  Not sure how I would do this without needing to traverse the list anyway.  Thoughts?

0

Share this post


Link to post
Share on other sites

Yeah, if you used a list you would have to traverse it to check it isn't already in the list in that case.

 

If it would be a programming error to add the same handler twice, just check in debug mode only and assert.

 

Otherwise you are looking at some kind of associative container (like C++ map, unordered_map, set, unordered_set, etc.) to do fast lookup/insertion/removal. Probably overkill. EDIT: And prevents any ordering by insertion order you may have wanted anyway.

 

But in general if you need to traverse an entire list to add something to the end, either add it to the beginning instead, or use a doubly linked list and track the head and tail nodes (and add it at the tail). Lists are pretty bad for efficiency anyway these days due to caches, but due to their simplicity it is usually the go to dynamic container in C (people don't seem to like implementing their own version of C++ vector, dynamic arrays tend not to be resized much in C).

Edited by Paradigm Shifter
1

Share this post


Link to post
Share on other sites

Just to complete this.  I had a couple of issues that in the code that I resolved.  I just wanted update incase it may help others.

 

First, in my registerEvent function, I was stupidly trying to traverse my list by incrementing a pointer to the head of the list.  Below is some code that works and hopefully can help others.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_NAME_LENGTH 10

/********************************************************************
	STRUCTURES AND ENUMS FOR
	EVENT HANDLING FUNCTIONS
********************************************************************/
typedef enum Events{
	TEST1,
	TEST2,
	TEST3,
	MAX_EVENTS
}e_Events;

typedef void (*callback) (void *);

typedef struct EventHandlers{
	callback cb;
	struct EventHandlers *next;
} s_EventHandlers;

s_EventHandlers *listeners[MAX_EVENTS];

/********************************************************************
	FORWARD DECLARES FOR
	EVENT HANDLING FUNCTIONS
********************************************************************/
void InitListeners(s_EventHandlers *handlers[], int size);
void DestroyListeners(s_EventHandlers *handlers[], int size);
int RegisterEvent(e_Events event, callback cb);

/********************************************************************
	TEST EVENT HANDLERS FUNCTIONS
********************************************************************/
void Test1Handler1(void *data){
	printf("In Test1 Handler 1 %s\n", (char*)data);
}
void Test1Handler2(void *data){
	printf("In Test1 Handler 2 %s\n", (char*)data);
}
void Test1Handler3(void *data){
	printf("In Test1 Handler 3 %s\n", (char*)data);
}
void Test1Handler4(void *data){
	printf("In Test1 Handler 4 %s\n", (char*)data);
}
void Test2Handler1(void *data){
	printf("In Test2 Handler 1 %s\n", (char*)data);
}
void Test3Handler1(void *data){
	printf("In Test3 Handler 1 %s\n", (char*)data);
}
void Test3Handler2(void *data){
	printf("In Test3 Handler 2 %s\n", (char*)data);
}

/*********************************************************************
	MAIN ENTRY POINT
 ********************************************************************/

int main(int argc, char *argv[])
{
	s_EventHandlers *handlers = NULL;
	char data[] = "this is the data";
	
	InitListeners(listeners,MAX_EVENTS);
	
	if(RegisterEvent(TEST1, Test1Handler1)==-1)
		printf("duplicate test handler\n");
	if(RegisterEvent(TEST1, Test1Handler2)==-1)
		printf("duplicate test handler\n");	
	if(RegisterEvent(TEST1, Test1Handler2)==-1)
		printf("duplicate test handler\n");	
	if(RegisterEvent(TEST1, Test1Handler4)==-1)
		printf("duplicate test handler\n");	
	if(RegisterEvent(TEST2, Test2Handler1)==-1)
		printf("duplicate test handler\n");
	if(RegisterEvent(TEST3, Test3Handler1)==-1)
		printf("duplicate test handler\n");
	if(RegisterEvent(TEST3, Test3Handler2)==-1)
		printf("duplicate test handler\n");
	
	handlers = listeners[TEST1];
	for(; handlers != NULL; handlers = handlers->next){
		handlers->cb(data);
	}
	
	handlers = listeners[TEST2];
	for(; handlers != NULL; handlers = handlers->next){
		handlers->cb(data);
	}
	
	handlers = listeners[TEST3];
	for(; handlers != NULL; handlers = handlers->next){
		handlers->cb(data);
	}
	
	DestroyListeners(listeners,MAX_EVENTS);
	
	return 0;
}

int RegisterEvent(e_Events event, callback cb){
	s_EventHandlers *handlers = listeners[event];

	if (handlers == NULL){  
		if(!(handlers = (s_EventHandlers*) malloc(sizeof(s_EventHandlers))))
			return 0; // error returned from malloc

		handlers->cb = cb;
		handlers->next = NULL;
		listeners[event] = handlers;
	} else { 
		while (handlers->next != NULL){	
			// handlers already registered for this event
			// check to see if it is a redundant handler for this event
			handlers = handlers->next;

			if (handlers->cb == cb)
				return -1;
		}

		s_EventHandlers *nextHandler;
		if (!(nextHandler = (s_EventHandlers*) malloc(sizeof(s_EventHandlers))))
			return 0; // error returned from malloc
		
		nextHandler->cb = cb;
		nextHandler->next = NULL;
		
		handlers->next = nextHandler;
	}	

	return 1;
}

void InitListeners(s_EventHandlers *handlers[], int size){
	int i;
	for (i = 0; i < MAX_EVENTS; i++){
		handlers[i] = NULL;
	}
}

void DestroyListeners(s_EventHandlers *handlers[], int size){
	int i;
	s_EventHandlers *deleteMe, *next;
	for (i = 0; i < MAX_EVENTS; i++){
		deleteMe = handlers[i];
		
		while (deleteMe){
			next = deleteMe->next;
			free(deleteMe);
			deleteMe = next;
		}
	}
} 
Edited by DeafManNoEars
0

Share this post


Link to post
Share on other sites

One things you should consider.  Often times, for an event, in the callback, the user may want to always pass it some data, typically called UserData.  

So, I would suggest adding a void* to the struct, and allow that data to be passed to the RegisterEvent() as well as to the callback.  Like this:

 

Also, I think you should allow one callback to register for multiple events, but also add the event type to the callback parameter..  Too often, an event might be very similar, and most of it could be handled by the same function, but for a minor difference.

 

To illustrate what I mean

/* NOTE, doesn't have to be malloc'd; if this struct lives in the main() function
    you could just derefence it via &MyData when calling RegisterEvent() */
s_MyData* MyData = malloc(sizeof(s_MyData));
 
/* fill in MyData */
...
 
RegisterEvent(MY_EVENT, MyEventHandler, MyData);
RegisterEvent(MY_OTHER_RELATED_EVENT, MyEventHandler, MyData);
 
...
 
/* This is the event Handler */
void MyEventHandler(e_Events event, void* eventData, void* userData)
{
...
  if (event == MY_OTHER_RELATED_EVENT) {
    /* do something special */
  }
}

 

That adds more flexibility to it IMO.

 

Either way, it looks good.

1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0