473,503 Members | 1,691 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function Pointer + Pass Function Name as String

4 New Member
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
7 8390
weaknessforcats
9,208 Recognized Expert Moderator Expert
// 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
dries
4 New Member
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
9,208 Recognized Expert Moderator Expert
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
dries
4 New Member
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
9,208 Recognized Expert Moderator Expert
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
dries
4 New Member
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
12 New Member
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

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

Similar topics

58
10046
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
8
29012
by: Tweaxor | last post by:
Hey, I was trying to figure out was it possible in C to pass the values in an array from one function to another function. Is the possible in C? ex. y is the array that holds seven values If...
7
5156
by: Mike D. | last post by:
I have a problem with a dynamic library I am developing, but it is really more of a pointer issue than anything else. Hopefully someone here can lend me some assistance or insight into resolving...
13
2332
by: dimitris67 | last post by:
How can I replace an occurence of p(a string) in an other string(s) with np(new string).. char* replace _pattern(char *s,char *p,char *np) PLEASE HELP ME!!!!!
9
5050
by: cmk128 | last post by:
Hi Why put * in front of the function name in the declaration? int (*write)(struct inode *, struct file *, const char *, int); thanks from Peter (cmk128@hotmail.com)
5
4995
by: sfeher | last post by:
Hi All, I need to call a function(loaded with appendChild) for which I have the name as a string. .... var fnName = 'fn1'; var call = fnName + '('+ param +' )'; eval(call);
3
3628
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules'...
19
1813
by: Adam | last post by:
Hi, I'd like to return an (arbitrary length) string array from a function so that after calling the array I've got a list of strings I can access. After much perusing of the internet I found a...
4
6654
by: S. | last post by:
Hi all, I have the requirement that I must pass-by-reference to my function addStudent() and getAge() functions where my getAge() function is within the addStudent() function. I am able to...
0
7084
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7278
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7328
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6991
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7458
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5013
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3167
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
380
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.