getmousestate function Open BGI library - c

I am currently using the out of date open BGI library for C as that is what my uni wants us to do but I can't figure out how to use this function.
extern void getmousestate(g_mousestate *state);
Definition:
void getmousestate(g_mousestate * state)
{
CHECK_GRAPHCS_INITED
state->x = sharedStruct->mouseX;
state->y = sharedStruct->mouseY;
state->buttons = sharedStruct->mouseButton;
}
g_mousestate Definition:
typedef struct mousestate {
int x, y;
int buttons;
}g_mousestate;
sharedStruct definition:
static SHARED_STRUCT * sharedStruct;
SHARED_STRUCT Definition:
typedef struct
{
int mouseX, mouseY;
int mouseButton;
int keyCode;
int keyLetter;
int visualPage;
} SHARED_STRUCT;
The sort of thing I was trying to do to call:
g_mousestate *a;
getmousestate(a->x);
But I don't know what to initialize a to...
I assumed this function could tell me what position the mouse is in and what buttons are being pressed etc, but I can't figure out how to call the function properly. Very much a beginner here, any help would be appreciated.

OK, beginner, let's start. You want to do:
g_mousestate *a;
getmousestate(a->x);
to get the x-position of the mouse. First note that you have declared a as a pointer, but no memory has been allocated for it (it points to nothing yet). So first you must have memory for the g_mousestate object:
g_mousestate a;
getmousestate(&a);
Now a is no longer a pointer but an object and you pass a pointer to the getmousestate function by taking the address of a with the & operator ("address-of").
You need to do no more since, if you look at the definition of the function, you see that all members are filled in by it.

Related

Why do I have to pass a pointer to a pointer in this case

This question is builds on a previous question from me.
There I had this construct. It uses SDL2:
void init_window(SDL_Window *window)
{
window = SDL_CreateWindow(…);
}
int main(void)
{
SDL_Window *window;
init_window(window);
}
This didn't work. The answer suggested, I used *&window as a function parameter instead, and it worked great.
I rewrote the *&window to **window as the following:
void init_window(SDL_Window **window)
{
*window = SDL_CreateWindow(…);
}
int main(void)
{
SDL_Window *window;
init_window(&window);
}
And it also works. But I still don't understand why the first version doesn't work. I looked up the implementation details of SDL_Window and it's just a normal typedef of a struct to put it into ordinary namespace. SDL_CreateWindow returns SDL_Surface *.
To picture my dilemma, I wrote this simple program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Person
{
char *name;
int age;
} Person;
Person *person_create(char *name, int age)
{
Person *who = malloc(sizeof(Person));
who->name = strdup(name);
who->age = age;
return who;
}
void person_get_old(Person *who)
{
who->age += 30;
}
int main(void)
{
Person *susan = person_create("Susan", 23);
person_get_old(susan);
printf("%i\n", susan->age);
}
This prints 53 just as expected, without me having to use pointer to pointer semantics. What is the difference between my implementation and that one of SDL2. This is no SDL2 question, as the one that answered my previous question could answer this without any knowledge of SDL2, so there seems to be some implementation detail I missed. Hope somebody can enlighten me.
Here's a simpler example to illustrate:
void foo(int p) //create new copy of int
{
p = 0; //modify copy, original is unchanged
}
void bar(int* p) //create new copy of pointer
{
*p = 0; //modify object pointer is set to
}
In your SDL example, you were trying to do foo. The goal was to set the pointer to a new value. However, you only copied the pointer and all changes were done to the copy.
In your Person example, you were doing bar. You had an object that was being pointed to, and you wanted to modify it. The correct way to do that is pass it by pointer (or reference).
Since you have an object you want to modify, you need to pass it by pointer (or reference). Since that object is a pointer itself, it will be a pointer to pointer.
The difference between your implementation and that of SDL2 is that in your implementation returns a pointer and the calling code assigns it to a variable.
In the SDL2 implementation, the called function wants to store the pointer, and you want it stored in an existing pointer defined by the calling code. It needs to know where to store the pointer, so it needs a pointer to the pointer.

Where is this pointer actually pointing?

I'm trying to learn c using learncodethehardway c book. In ex19 I have the following code:
int Monster_init(void *self)
{
Monster *monster = self;
monster->hit_points = 10;
return 1;
}
int Monster_attack(void *self, int damage)
{
Monster *monster = self;
printf("You attack %s!\n", monster->proto.description);
monster->hit_points -= damage;
if(monster->hit_points > 0) {
printf("It is still alive.\n");
return 0;
} else {
printf("It is dead.\n");
return 1;
}
}
Object MonsterProto = {
.init = Monster_init,
.attack = Monster_attack
};
This is the Object structure:
typedef struct {
char *description;
int (*init)(void *self);
void (*describe)(void *self);
void (*destroy)(void *self);
void *(*move)(void *self, Direction direction);
int (*attack)(void *self, int damage);
} Object;
And this is the Monster structure:
struct Monster {
Object proto;
int hit_points;
};
I'm having a tough time wrapping my head around the Monster_init and Monster_attack functions. I have a MonsterProto variable of type Object defined and inside there .init is set to the Monster_initfunction and .attack is set to the Monster_attack function.
I think I understand the notion of void in terms of declaring a function that has side effects but doesn't need to return something. What I don't understand is what exactly is the void *self pointer pointing at and why does it allow me to call a function with no arguments? What is the purpose of the self pointer?
I didn't want to include too much code here but if this is not enough context to answer the question, then you can find all the code here.
I appreciate any pointers in the right direction; nu pun intended :)
This code seems to be effectively implementing a kind of object-oriented approach.
self is the address of the struct Monster that you pass to those functions. Each of those functions operates on an individual object, and passing in the pointer to that object is how they know which one to work on.
This:
.init = Monster_init,
is not "calling a function with no arguments" - the init member of your struct is a pointer to a function returning an int and accepting a single void * parameter, and that line assigns the address of Monster_init() to it. This way, if you have a pointer to an object, you can call int n = myobject->proto.init(&myobject); or similar without knowing which actual function gets called. With a different object, you might be calling a different function with the same line of code.

Structure returning function

In C component selection, what is the benefit of structure-returning function? for example:
struct S {
int a, b;
} x;
Why is it that I can assign the above struct as a function as shown below, Is there any benefit of doing this?
extern struct S f(); /* Why is this neccesary? */
x = f(); /* Is this accurate */
Open my eyes on this guys.
It's just a function that happens to return a struct. There's nothing more to it than that. You wouldn't be surprised to see a function return an int, why be surprised when one returns a struct?
As an aside, the extern is superfluous here because that is the default storage class for functions.
It is useful so that you can return multiple values from a function.
For example, you can use it like this
struct Point {
int x;
int y;
};
struct Point getMousePos()
{
struct Point pos;
pos.x = 567;
pos.y = 343;
return pos;
}
int main()
{
struct Point mouse_pos = getMousePos();
printf("Mousepos %d,%d\n", mouse_pos.x, mouse_pos.y");
}
The function can be forward declared with extern (this would normally be done in a header file), so that other functions know its prototype i.e. its parameters and return type, even if the function is itself defined in another file.
If you get a copy of a struct instead of a pointer to it, you know that you never have to worry about free()ing it, or whether there are any data races where one thread is writing to the struct while another reads from it, or whether the pointer returned by the function will be invalidated by some action that might be outside of your control.

C find which pointer called function

Scenario:
There are multiple C structs, each of which contains a function pointer to the same function. These pointers can be different if necessary (pointers to pointers, etc.), but must all point, eventually, to the same function.
Problem:
When the function is called from one of the pointers, I need to retrieve, within the function, which struct it was called from.
e.g.
typedef struct A {
void * (*func)();
... /* Custom properties */
} * A;
typedef struct B {
void * (*func)();
... /* Custom properties */
} * B;
A a_init() {
A a;
... /* Custom initialisation, allocation, etc. */
a->func = myFunc;
return a;
}
B b_init() {
B b;
... /* Custom initialisation, allocation, etc. */
b->func = myFunc;
return b;
}
int main () {
A a = a_init();
void *something = a->func();
}
void * myFunc () {
// Need to get pointer to the instance of the struct this was called from here
}
Is there any way I can retrieve a pointer to the caller within myFunc? If necessary, I was thinking of creating pointers to pointers, etc. to the function, so each instance of an object would have a different pointer, and store all of them in a central location to match them up, but that obviously won't work if I can't even find the instance of the object or the pointer which was used. Any ideas?
Edit:
The question was intended a bit more broadly than I seem to have put it. Currying would be a great solution, if anyone has any ideas as to how to implement it in C. I had some ideas, but I just ended up coming right back to this spot with it.
I don't think there is any way within the language to do that, without explicitly passing some identifier (as an argument or a global) to myFunc. The address of a_init() exists somwhere within the call stack, but it's not accessible from the program.
It's like if somebody showed up at your door unannounced, how would you find out where that person came from without asking?
You can't do that. What you may do, however, is define your structs like this:
typedef struct A {
/* ... */
void *(*func)(void *);
} A;
typedef struct B {
/* ... */
void *(*func)(void *);
} B;
And your function like this:
void *myFunc(void *the_struct) {
/* ... */
}
And call like this:
A a = a_init();
void *something = a->func(a);
Alternatively, if you don't care about portability and for some reason need to be able to call it like a->func(), you may be able to create thunks/trampolines that add in the argument.
Can't be done.
In C++ when you call member functions the compiler implicitly adds this as the first function argument. Mimicking obj->method() syntax in C won't work because there's no implicit this.
This doesn't mean that OO is impossible in C, simply that you can't use the same syntax as C++ or Java do to it. It can still be done, but you have to be explicit:
void * myFunc (void *this) {
...
}
a->func(a);
b->func(b);

when do we use function pointers

I am trying to understand the existing code.
When do we actually go for function pointers? specially like the one below.
struct xx
{
char *a;
(*func)(char *a, void *b);
void *b;
}
struct xx ppp[] = { };
then check sizeof(ppp)/sizeof(*ppp);
when do we go with such kind of approach?
sizeof array / sizeof *array is a way of finding out how many elements are in an array. (Note that it must be an array rather than a pointer.) I'm not sure how that's related to your function pointer question.
Function pointers are used to store a reference to a function so that it can be called later. The key thing is that a function pointer needn't always point to the same function. (If it did, you could just refer to the function by name.)
Here's an example based on your code (although I could provide a better one if I knew what your code was supposed to do.
char *s1 = "String one";
char *s2 = "String two";
void f(char *a, void *b) {
/* Do something with a and b */
}
void g(char *a, void *b) {
/* Do something else with a and b */
}
struct xx {
char *a;
void (*func)(char *a, void *b);
void *b;
}
struct xx ppp[] = { {s1, f, NULL}, {s2, g, NULL} };
int main(int argc, char **argv) {
for (int i = 0; i < (sizeof ppp / sizeof *ppp); i++) {
ppp[i].func(ppp[i].a, ppp[i].b);
}
}
There are two major uses (that I know of) for function pointers in C.
1. Callbacks
You have some sort of event-driven framework (a GUI is one of the easiest examples), and the program wants to react to events as they happen. Now you can do that with an event pump, like
while (event *e = get_one_event()) {
switch (e->type) {
case EVT_CLICK:
...
}
}
but that gets tiring after a while. The other major alternative is callbacks. The program defines a bunch of functions to handle different events, and then registers them with the library: "when event X happens, call function Y" -- so of course, the library is going to receive a function pointer, and call it at the relevant time.
2. Objects (function tables / vtables)
If you've done OO in most other languages, this should be fairly easy for you to picture. Imagine an object as a struct that contains its members and then a bunch of function pointers (or, maybe more likely, its members and a pointer to another struct representing its class, that contains a bunch of function pointers). The function pointers in the table are the object's methods. GLib/GObject is a big user of this technique, as is the Linux kernel (struct file_operations, struct device_driver, struct bus_type, and many many more). This lets us have an arbitrary number of objects with different behavior, without multiplying the amount of code.
When do we actually go for function pointers? specially like the one below.
You use function pointer when you want to make something more abstract.
By example, suppose your application has a graphical toolbox with a certain number of buttons. Every button corresponds to an instance of a certain struct.
The button structure can contain a function pointer and a context:
typedef struct {
void (*press_button) (void *context);
void *context;
/* Here some other stuff */
} Button;
When the user clicks the button, the event is something like
void event_click (Button *b)
{
b->press_button(b->context);
}
The point in doing this is that you can use always the same structure for each button:
Button * create_button (void (*callback) (void *), void *context, /* other params */
{
Button *ret = malloc(sizeof(Button));
if (ret != NULL) {
ret->callback = callback;
ret->context = context;
/* Assign other params */
}
...
return ret;
}
So when you build your toolbox you probably do something like
Button * toolbox[N];
toolbox[0] = create_button(function1, (void *)data, ...);
toolbox[1] = create_button(function2, (void *)something, ...);
...
toolbox[N-1] = create_button(functionN, (void *)something_else, ...);
Also when you create some function pointer, always carry some contxt information (like I did with the context field of the struct). This allows you to avoid global variables, thus you can get a robust and reentrant code!
Note:
This method is awesome, but if you deal with C++ you may prefer to use object orientation and replace callbacks with derivaton from abstract classes. By doing this you also don't need to carry the context, since the class will do it for you.
Edit in answer of first comment:
The current code I am going through is related to file IO. setting an environment variable and creating symbolic links between files, copying data from one file to another, etc. I am not understanding why do we need to call these functions at run time using function pointers. we can as well call them directly.
In fact you can do what you need without using function pointers. If I do understand well your problem, you are trying to understand someone else's code, which is doing what you listed with function pointers.
Personally I don't use this feature unless I need it but if you post here some additional code maybe we can try to understand it better.

Resources