I'm trying to write code in C (for embedded application), in which there would be event callback (caused by pressing a button) calling different functions, depending on GUI screen that is currently displayed.
Ideally I would like to "define" function like: keyXPressed() many times and programming different actions in different parts of the code (like on Screen1 do this and on Screen2 do that), so that single callback would always refer to one that is currently on. I know that multiple definitions of the functions are probably not the way and presumably some object-oriented techniques will be involved.
What are the ways of achieving such functionality in simple and elegant manner?
Use a function pointer.
void (*keyPressed)(screen *);
void keyXPressed(screen *s) {
// code here
}
void keyYPressed(screen *s) {
// code here
}
Then you can assign keyPressed = keyXPressed; or keyPressed = keyYPressed;, and call keyPressed(screen1);
Related
I've been messing around with SDL2 in c and was wondering how to abstract code away without using too many function parameters. For example, in a normal gameplay loop there is usually an input, update, render cycle. Ideally, I would like this to be abstracted as possible so I could have functions called "input", "update", "render", in my loop. How could i do this in c without having those functions take a ludicrous amount of parameters? I know that c++ kind of solves this issue through classes, but I am curious and want to know how to do this in a procedural programming setting.
So far, I can't really think of any way to fix this. I tried looking it up online but only get results for c++ classes. As mentioned before, I want to stick to c because that is what i am comfortable with right now and would prefer to use.
If you have complex state to transport some between calls, put that in a struct. Pass a pointer to that as the sole argument to your functions, out at least as the first of very few.
That is a very common design pattern on C code.
void inputstep(struct state_t* systemstate);
void updatestep(struct state_t* systemstate);
void renderstep(struct state_t* systemstate, struct opengl_context_t* oglctx);
Note also that it is exactly the same, if not even more (due to less safety about pointers), overhead as having a C++ class with methods.
this in a functional programming setting.
Well, C is about as far as you get from a purely functional language, so functional programming paradigms only awkwardly translate. Are you sure you didn't mean "procedural"?
In a functional programming mindset, the state you pass into a function would be immutable or discarded after the function, and the function would return a new state; something like
struct mystate_t* mystate;
...
while(1) {
mystate = inputfunc(mystate);
mystate = updatefunc(mystate);
…
}
Only that in a functional setting, you wouldn't re-assign to a variable, and wouldn't have a while loop like that. Essentially, you wouldn't write C.
I have come across the function pointers. I know understand how this works. But i am not pretty sure, in what situation it will use. After some google and other search in Stack Overflow. I came know to know that it will use in two case
when callback mechanism is used
Store a array of functions, to call dynamically.
In this case also, why don't we call function directly. In the call back Mechanism also, as particular events occur, callback pointer is assigned to that function(Address). Then that is called. Can't we call function directly rather than using the function pointer. Can some some one tell me, what is the exact usage of Function pointer and in what situation.
Take a look at functions needing a callback, like
bsearch or qsort for the comparator, signal for the handler, or others.
Also, how would you want to program other openly-extensible mechanisms, like C++-like virtual-dispatch (vptr-table with function-pointers and other stuff)?
In short, function-pointers are used for making a function generic by making parts of the behavior user-defined.
One of the situation when function pointers would be useful is when you are trying to implement callback functions.
For example, in a server that I've been implementing in C and libevent accepts a message from clients and determine what to do. Instead of defining hundreds of switch-case blocks, I store function pointer of function to be called in a hash table so the message can be directly mapped to the respective function.
Event handling in libevent API(read about event_new()) also demonstrates the usefulness of having function points in APIs such that users can define their own behaviour given a certain situation and need not to modify the master function's code, which creates flexibility while maintaining certain level of abstraction. This design is also widely used in the Kernel API.
You said:
In the call back Mechanism also, as particular events occur, callback pointer is assigned to that function(Address).
Callback functions are registered at a very different place than where the callback functions are called.
A simple example:
In a GUI, the place where you register a function when a button is pressed is your toplevel application setup. The place where the function gets called is the implementation of the button. They need to remain separate to allow for the user of the button to have the freedom of what they wish to do when a button is pressed.
In general, you need a function pointer when the pointer needs to be stored to be used at a future time.
In the case of a callback situation, including interrupt driven code, a sequence of call backs or interrupts may occur for a single logical process. Say you have a set of functions like step1(), step2(), ... , to perform some process where a common callback is being used to step through a sequence. The initial call sets the callback to step1(), when step1() is called, it changes the pointer to function to step2() and initiates the next step. When that step completes, step2() is called, and it can set a pointer to function to step3(), and so on, depending on how many steps it takes to perform the sequence. I've mostly used this method for interrupt driven code.
Sometimes I use function pointers just to make (as I see it) the code more legible, and easier to change. But this is a matter of taste, there is no one 'correct' way. It's possible that the function pointer code will be slower, but probably only slightly and of course as far as performance goes it's always a matter of measuring, and usually more a matter of choosing better algorithms than of micro-optimisation.
One example is when you have two functions, with identical and long argument lists and sometimes you want to call one and sometimes the other. You could write
if ( condition)
{ one( /* long argument list */);
}
else
{ other( /* long argument list */);
}
or you could write
(condition ? one : other)(/* long argument list */);
I prefer the second as there is only one instance of the long argument list, and so it's easier to get right, and to change.
Another case is implementing state machines; one could write
switch( state)
{ case STATE0: state = state0_fun( input); break;
// etc
}
or
typedef int (*state_f)( void*);
state_f statefs[] = { state0_fun /* etc */}
state = statefs[ state](input);
Again I find the second form more maintainable, but maybe that's just me.
I write code in C. I have been striving to write more testable code but I am a little
confused on deciding between writing pure functions that are really good for testing
but require smaller functions and hurt readability in my opinion and writing functions
that do modify some internal state.
For example (all state variables are declared static and hence are "private" to my module):
Which of this is more testable in your opinion:
int outer_API_bar()
{
// Modify internal state
internal_foo()
}
int internal_foo()
{
// Do stuff
if (internal_state_variable)
{
// Do some more stuff
internal_state_variable = false;
}
}
OR
int outer_API_bar()
{
// Modify internal state
internal_foo(internal_state_variable)
// This could be another function if repeated many
// times in the module
if (internal_state_variable)
{
internal_state_variable = false;
}
}
int internal_foo(bool arg)
{
// Do stuff
if (arg)
{
// Do some more stuff
}
}
Although second implementation is more testable wrt to internal_foo as it has no sideeffects but it makes bar uglier and requires smaller functions that make it hard for the reader to even follow small snippets as he has to constantly shift attention to different functions.
Which one do you think is better ? Compare this to writing OOPS code, the private functions most of the time use internal state and are not pure. Testing is done by setting up internal state on a mock object instance and testing the private function. I am getting a little confused on whether to use or whether to pass in internal state to private functions for the sake of "testability"
Whenever writing automated tests, ideally we want to focus on testing the specification of that unit of code, not the implementation (otherwise we create fragile tests that will break whenever we modify the implementation). Therefore, what happens internally in the object should not be of concern to the test.
For this example, I would look to build a test that:
Executes the test by calling outer_API_bar.
Asserts that the correct behavior of the call using other publicly accessible functions and/or state (there must be some way of doing this, as if the only side effect of calling outer_API_bar was internal to this unit of code, then calling this function could not impact your wider application in any way, and essentially be useless).
This way, you are able to keep the fact that you use functions like internal_foo, and variables like internal_state_variable as implementation details, which you can freely change when refactoring your code (i.e. to make it more readable) without having to change your tests.
NOTE: This suggestion is based on my own personal preference for only testing public functions, and not private ones. You will find much debate on this topic where some people pose good arguments for testing private functions being a valid thing to do.
To answer your question very specifically pure functions are waaaaay more 'testable' than any other kind of abstraction. The more pure functions you can include, the more testable your code would be. As you rightly mention, this can come at the cost of readability, and I am sure there are other trade offs to consider. My suggestion would be to aim for more pure functions and look for other techniques that would allow you to compensate on the readability side of things.
Both snippets are testable via mocks. The second one, however, has the advantage that you can also check the argument of internal_foo(bool arg) for an expected value of true or false when the mock for internal_foo() is invoked. In my opinion, that would make for a more meaningful test.
Depending on the rest of the code that we don't know, testing without mocks may be more difficult.
I have the example GTK C application from [1] building and working as expected. I have a pretty little UI application with a + and - button to increment/decrement a value stored in a global variable, and render it in the application in a text label.
I rarely ever work with GUI applications, and I do 99% of my work in C. I have two key questions with respect to tidying up this example and using it as the basis of a project.
Is it possible to have some alternative to global variables, like a
custom struct I create in main(), and have every callback handler reference
it by changing the function protocol for increase()?
Code:
// Can this function protocol be modified?
void increase(GtkWidget *widget, gpointer label) {
count++;
sprintf(buf, "%d", count);
gtk_label_set_text(GTK_LABEL(label), buf);
}
g_signal_connect(minus, "clicked", G_CALLBACK(decrease), label);
Is there a simple means of creating a separate thread to help manage the GUI? For example, if I have a button tied/connected to a function that would take a minute to complete, is there a universally-accepted means of firing off a separate pthread that allows me to have a button or command to cancel the operation, rather than the entire UI app being blocked for the whole minute?
Thank you.
References
Cross Compiling GTK applications For the Raspberry Pi, Accessed 2014-02-20, <http://hertaville.com/2013/07/19/cross-compiling-gtk-applications-for-the-raspberry-pi/>
Yes, you can pass anything you like as the last argument to signal handlers (gpointer is a typedef for void*) just create the structure containing the label widget and the counter variable in main(), pass it as the last argument to g_signal_connect and cast it back to the proper type in your callback.
For running a calculation in another thread and delivering the result to the gtk main loop I'd look at GTask, in particular g_task_run_in_thread_async.
I'm writing a wrapper around a C library in Objective-C. The library allows me to register callback functions when certain events occur.
The register_callback_handler() function takes a function pointer as one of the parameters.
My question to you gurus of programming is this: How can I represent an Objective-C method call / selector as a function pointer?
Would NSInvocation be something useful in this situation or too high level?
Would I be better off just writing a C function that has the method call written inside it, and then pass the pointer to that function?
Any help would be great, thanks.
Does register_callback_handler() also take a (void*) context argument? Most callback APIs do.
If it does, then you could use NSInvocation quite easily. Or you could allocate a little struct that contains a reference to the object and selector and then cobble up your own call.
If it only takes a function pointer, then you are potentially hosed. You need something somewhere that uniquely identifies the context, even for pure C coding.
Given that your callback handler does have a context pointer, you are all set:
typedef struct {
id target;
SEL selector;
// you could put more stuff here if you wanted
id someContextualSensitiveThing;
} TrampolineData;
void trampoline(void *freedata) {
TrampolineData *trampData = freedata;
[trampData->target performSelector: trampData->selector withObject: trampData-> someContextualSensitiveThing];
}
...
TrampolineData *td = malloc(sizeof(TrampolineData));
... fill in the struct here ...
register_callback_handler(..., trampoline, td);
That is the general idea, anyway. If you need to deal with non-object typed arguments and/or callbacks, it gets a little bit trickier, but not that much. The easiest way is to call objc_msgSend() directly after typecasting it to a function pointer of the right type so the compiler generates the right call site (keeping in mind that you might need to use objc_msgSend_stret() for structure return types).