Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Event Handlers In C


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
7 replies to this topic

#1 NotYourAverageUser   Members   -  Reputation: 500

Like
0Likes
Like

Posted 07 August 2013 - 02:09 PM

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, 07 August 2013 - 02:11 PM.


Sponsor:

#2 smr   Members   -  Reputation: 1676

Like
1Likes
Like

Posted 07 August 2013 - 02:52 PM

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).



#3 NotYourAverageUser   Members   -  Reputation: 500

Like
0Likes
Like

Posted 08 August 2013 - 06:33 AM

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, 08 August 2013 - 07:25 AM.


#4 Paradigm Shifter   Crossbones+   -  Reputation: 5410

Like
1Likes
Like

Posted 08 August 2013 - 06:48 AM

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, 08 August 2013 - 06:51 AM.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#5 NotYourAverageUser   Members   -  Reputation: 500

Like
0Likes
Like

Posted 08 August 2013 - 07:21 AM


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?



#6 Paradigm Shifter   Crossbones+   -  Reputation: 5410

Like
1Likes
Like

Posted 08 August 2013 - 07:30 AM

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, 08 August 2013 - 07:33 AM.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#7 NotYourAverageUser   Members   -  Reputation: 500

Like
0Likes
Like

Posted 08 August 2013 - 02:45 PM

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, 08 August 2013 - 02:46 PM.


#8 BeerNutts   Crossbones+   -  Reputation: 2980

Like
1Likes
Like

Posted 14 August 2013 - 01:54 PM

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.


My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS