Building: hooks.h
Calling functions in a .so file from outside that .so file
In hooks.h
In C, you can't export functions from one dynamic module and use them elsewhere. What would it do when the module gets unloaded?
To get around this, we have include/hooks.h
, which is part of the main mud executable and can therefore export whatever it wants.
Lets take one of the lines from hooks.h
as an example:
EXTERN void(*START_PROGRAM)(MudObject *, MudObject *, MudObject *);That means that somewhere that we don't know about, there is a function which takes three
MudObject*
's and returns a void
, and we have a function pointer to it, called START_PROGRAM
.
This function is actually used to start simulator programs running.
In the module that contains your function
If we look inholos.cc
, we will see, at the bottom of the file in the startup() section that gets run when the module is loaded, the line:
START_PROGRAM = start_program;This makes the function pointer we defined in
hooks.h
point to something we know about, namely:
static void start_program(MudObject *player, MudObject *deck, MudObject *prog)This is a function that takes the same type parameters, and returns the same type as the function pointer we defined in
hooks.h
. It is strongly advised that the function pointer be an uppercase version of your function. It will just cause brain-ache if it isn't.
We will also see the line:
#define CLEANUP START_PROGRAM = 0;
CLEANUP
gets called when the module gets unloaded.
So now we have code that makes the function pointer point to somewhere useful when the holos.so
module is loaded, and point to NULL
when it is unloaded. That is all you need to be able to use your function from elsewhere.
In the module you want to call your function from
Now you've got a function pointer that, when the right module is loaded, points to a useful function, you need to use it.
In the case of START_PROGRAM
, it gets used from objects.cc
. In there, we see the lines:
if (START_PROGRAM) START_PROGRAM(who, who->owner, program); else who->printf("Can't start program.\n");You must always check that the function pointer is pointing somewhere before you call it and handle the error if it isn't. It is possible that the module containing the function may not be loaded, but this other module is.