Jean-Daniel Gamache wrote:
Hi, I want to be able to call a function specified at run-time (in a string).
How can I do that in C++ ????
ie:
char myFunctionName[] = "myFunction";
void myFunction () {
}
//this is the tricky part i am wondering how i could call
// a function that is specified in my variable myFunctionName?
functionPtr = GetFunctionAddress(myFunctionName);
functionPtr();
The only portable way to do this is to place these in a registry.
This whole discussion very quickly leads to factories.
Let's start with somthig along the lines of what you did.
#include <cstring>
char myFunction1Name[] = "myFunction1";
void myFunction1 () {
}
char myFunction2Name[] = "myFunction2";
void myFunction2 () {
}
struct RegistryEntry {
const char * name;
void ( * func )();
};
RegistryEntry Registry[] =
{
{ myFunction1Name, & myFunction1 },
{ myFunction2Name, & myFunction2 },
};
int RegistryCount = sizeof( Registry ) / sizeof( * Registry );
void ( * GetFunctionAddress( const char * name ) )()
{
for ( int i = RegistryCount - 1; i >= 0; i -- )
{
if ( std::strcmp( name, Registry[i].name ) == 0 )
{
return Registry[i].func;
}
}
return 0;
}
OK - Problem number 1 - only functions that you compile into the
"Registry" are accessible.
Most reasons for doing this is so that they can load modules at a later
point in time and this system requires a recompilation of the array
"Registry".
The second thing, often you need some context and a collection of method
- oops, this is called a class.
The third thing, you'll want it to be able to do this with dynamically
loaded objects (.dll's or .so's).
The fourth thing, you'll want to be able to reliably unregister them as
well.
Anything else ? Oh yeah, network transparency - starting to look like
COM and Corba.
I have one of these factory frameworks which is a bunch of templates
that does most of this. It's a general purpose system. Let me know if
you're interested but it's far more involved than the system above.
G