cast to pointer to function

Hello all,
i'm experimenting a problem in trying to cast a char * variable to a
pointer to a function.
My problem is that I want to execute functions in threads, using the
pthread_create function.
The name of the functions are read in txt file at runtime.
So I want to do something like
char * func_to_run = scanf(the, good, args);
pthread_create (thread, attr, (magic cast)funct_to_run, arg);

In fact, what I need is not exactly a cast, it is something that gets
the pointer to the function that match the name in func_to_run.
The functions are compiled and linked somewhere in the executable.

Even better I would like to test, at runtime, that the provided name
in func_to_run is the name of a function that exists.

Advertisements

On 2007-07-19, etienne <> wrote:
> Hello all,
> i'm experimenting a problem in trying to cast a char * variable to a
> pointer to a function.
> My problem is that I want to execute functions in threads, using the
> pthread_create function.
> The name of the functions are read in txt file at runtime.
> So I want to do something like
> char * func_to_run = scanf(the, good, args);
> pthread_create (thread, attr, (magic cast)funct_to_run, arg);

This won't work because funct_to_run is not actually a pointer to a
function but just a pointer to the function name.
> Even better I would like to test, at runtime, that the provided name
> in func_to_run is the name of a function that exists.

I suggest that this is a bad idea, I don't think that you want every
function that exists in you program to be runnable by name from an
external source, how would you even get the arguments correct?

To do this you would have to use a platform specific solution such as
a dlopen/dlsym call. This makes the problem more complex (and OT).

There's probably a restricted set of functions with a standard
signature that are candidates for this type of execution. In this
case you could have a map of external name to function pointer, and
check this list when you are given the name of the function to call.

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!