By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,533 Members | 2,102 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,533 IT Pros & Developers. It's quick & easy.

Function Pointer + Pass Function Name as String

P: 4
Hello lads,

I'd like to do the following in C:

1. The user writes a function with predefined arguments and return value in a separate file.
2. The program is compiled as my written 'main' program and the file containing the user function included.
3. When the program is invoked, the user is asked how his function is named (f.e. function1).
4. The 'main' program calls and executes the user function.

The problem is, how can I cast the string-pointer, obtained from the user to a function-pointer? (If it can be done). It is easy to define the function-pointer, because I know the form of the function, but not to assign a function to the pointer at runtime.

This code illustrates what I mean:

Main program:

char funct_name[30];

// define function pointer (argument = int, return = int)
int (*pt2Funtion)(int);

// ask the user for his function name
printf("Enter funtion name: ");
scanf("%s", funct_name);

// assign the function to the pointer
// all we know is the name of the function
HOW CAN WE DO THIS?

// invoke function through its pointer
int res = (*pt2Function)(some_int);


User file:
// function to be called
int my_funtion(int arg){
return arg*2;
}


Thanks a lot for your help.
Greetz,
Dries.
Mar 24 '08 #1
Share this Question
Share on Google+
7 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
// assign the function to the pointer
// all we know is the name of the function
HOW CAN WE DO THIS?
The name of the function is the address of the function.

Like this:
Expand|Select|Wrap|Line Numbers
  1. size_t strlen(const char*);     //strlen function prototype
  2.  
  3. size_t (*fp)(const char*);      //function pointer
  4.  
  5. fp = strlen;                           //address pf strlen assigned to pointer
  6.  
  7. size_t len = fp("dries");         //len is 5
  8.  
You should not have to cast. Your function pointer needs to have the same argument types in the same order and return type as the the functions whose addresses are to be put inside the pointer.
Mar 24 '08 #2

P: 4
Hi,

thanks for your reply. But your answer is not quite what I like to do. I don't want to pass a string as an argument to a function, invoked through a pointer. That is easy indeed. The problem lies in the fact that I can't do this operation:

pt2Funtion = function_name;

Because I only know the name of the function that is to be invoked through a string donated to me while the program is running.

Let me explain by another example:

Suppose we have two functions:
void my_function(){ printf("Hello"); }

void other_function(){ printf("Goodbye"); }

These functions live somewhere in extra_functions.c

And then we have the main program, main.c:
void main(){
....
}

The thing is, the main program knows shit about the existence of my_function and other_function, but because we compile like:
gcc -c extra_functions.c
and then:
gcc main.c extra_functions.o
These two functions are compiled with main into the executable, so we should be able to execute them one way or another.

Now what I want to do is to be able to execute my_function or other_function or maybe some other function (with the same syntax as my_function and other_function though) I don't know about added by the user later in extra_functions.c (after recompilation). The only thing I know about is that the user will give me the name of the function he wants to run through a command line argument or a scanf("%s") call when main is invoked.
This is not a trivial task indeed. I don't even know if it can be done in C.

Thanks for all your help again. Any comment is appreciated.

Greets,
Dries.
Mar 24 '08 #3

weaknessforcats
Expert Mod 5K+
P: 9,197
Well, firstly, unless your .c files are compiled into object files that are linked into your executable, your functions in those files that do not include main() are not part of your program.

So, you have to compile all the code.

That said, if you have compiled these functions:

void my_function(){ printf("Hello"); }

void other_function(){ printf("Goodbye"); }

you could write a function that does this;

Expand|Select|Wrap|Line Numbers
  1. in main()
  2. {
  3.     DoIt("my_function", NULL, NULL);
  4. }
  5.  
Here you ask for the function by name and supply the address of an array that contains the arguments (NULL would be no arguments). How you design this array is up to you.

Then you could:
int DoIt(const char* str, Args* args, int numArgs)
{
if (!strcmp("my_function"))
{
my_function();
return 0; //success
}
return 1; //falure
}
[/code]

But this seems like a lot of fuss for low payoff.
Mar 24 '08 #4

P: 4
Dear,

this answer is still absolutely not what I mean. I suggest you read first more than once what I'm writing.

First of all, why are you telling me that I don't compile the functions by telling the gcc compiler first to compile extra_functions.c to object code by using the flag -c, and then to compile everything with gcc main.c extra_functions.o. Apparently you have never used gcc.

Secondly, you clearly don't understand my question. Maybe it is too advanced for you. In that case I suggest that you stop posting rubbish.
Everything you need to know is in the two previous posts. Just read it once more and think about it before posting anything.

Let me stress on the fact that the extra_functions.c is like a black box for main.c. Main.c doesn't know what functions are in there, especially it doesn't know their name. So it can't neither use strcmp to decide which function to run. The name of the function to run is given to main.c through user intervention. Main.c only knows that some function with this name exists in extra_functions.c, but it doesn't know which function names are in there at compile time. So the tricky part is to be able to obtain a pointer to the right function with the only available information being the function name captured in a string, filled-in at runtime.

I hope this information is enough for somebody to advance this topic a bit.
And please don't say things like: why do you need to know this for anyway? I just need to know if it can be done. From a scientific point of view let's say.

Thanks a lot. Greets,
Dries.
Mar 24 '08 #5

weaknessforcats
Expert Mod 5K+
P: 9,197
First of all, why are you telling me that I don't compile the functions by telling the gcc compiler first to compile extra_functions.c to object code by using the flag -c, and then to compile everything with gcc main.c extra_functions.o. Apparently you have never used gcc.
No. But I know how a build works. Unless the extra-functions object file is copied to your executable by the linker, there are no functions to execute at run time. I hope you understand that the C code is not available at run time.

Secondly, you clearly don't understand my question. Maybe it is too advanced for you. In that case I suggest that you stop posting rubbish.
Everything you need to know is in the two previous posts. Just read it once more and think about it before posting anything.
Nope. Just be aware that getting a function name from a user is not enought, you also need to get the arguments. Unless, it's some toy example where the functions have no arguments.

While I am at this point, I remind you to observe professional courtesy in your postings and do not engage in personal attacks.

Let me stress on the fact that the extra_functions.c is like a black box for main.c. Main.c doesn't know what functions are in there, especially it doesn't know their name. So it can't neither use strcmp to decide which function to run. The name of the function to run is given to main.c through user intervention. Main.c only knows that some function with this name exists in extra_functions.c, but it doesn't know which function names are in there at compile time. So the tricky part is to be able to obtain a pointer to the right function with the only available information being the function name captured in a string, filled-in at runtime.
I remind you that extra_functions.c is a source file. It is not available at run time. The only way it's available at run time is on your computer. I suppose you couild open extra_functions.c as a text inout file and search for the function name and form that deduce what kind of pointer you needm but unless you have compiled this file into your executable, there is no function to call.
Mar 25 '08 #6

P: 4
No. But I know how a build works. Unless the extra-functions object file is copied to your executable by the linker, there are no functions to execute at run time.
GCC invokes the linker 'ld' automagically in order to link all *.o files with the main executable. I guess u're using Wintendo.

I hope you understand that the C code is not available at run time.
So this is quite incorrect...

Nope. Just be aware that getting a function name from a user is not enought, you also need to get the arguments. Unless, it's some toy example where the functions have no arguments.
As I was telling in the previous posts, the functions have a predefined set of argument types and return value. These are filled in by the main function, once it has obtained a pointer to the function. The user must not provide them.

While I am at this point, I remind you to observe professional courtesy in your postings and do not engage in personal attacks.
I'm sorry. I was quite disappointed about the answers you are giving me.

I remind you that extra_functions.c is a source file.
Deuh, that's what files that end with a .c are.

It is not available at run time.
A I said, for numerous times, it is absolutely converted to assembly and available in the memory space of the running program.

The only way it's available at run time is on your computer.
Where else? On some server in a distant galaxy?


I suppose you couild open extra_functions.c as a text inout file and search for the function name
Why should I do that for? The user gave me the name of a function I need to run.

and form that deduce what kind of pointer you needm
Aha, and how do we do this if the only thing we know is the function name as a string?

but unless you have compiled this file into your executable, there is no function to call.
You're repeating yourself here...
Mar 25 '08 #7

Natasha26
P: 12
GCC invokes the linker 'ld' automagically in order to link all *.o files with the main executable. I guess u're using Wintendo.


You're repeating yourself here...
brrrr.... Look Dries, you should appreciate that someone actually volunteered to help. On another note, I think Cats has a good solution to try out.

(Besides the external location of your functions), it seems that you can get the desired function name (and arguments) from a user. Unfortunately this is only in string/char representation and can't be directly converted into a function name at runtime (if u can do that, let me know plz).

What Cats suggested is to use a method to compare the user input string to what you have in terms of function-name strings. Compare the two within an if/else control mechanism, if you get a match then call that function. I have to say at this point, why bother with function-pointers, just call the function straightaway.

I was checking this site when i saw ur question: http://www.newty.de/fpt/intro.html
Mar 26 '08 #8

Post your reply

Sign in to post your reply or Sign up for a free account.