ludo
ludo

Reputation: 1466

C - How to get a user defined function and turn it into a pointer?

I would like to know if there is any way of getting a user defined function (with two variables) from stdin in mathematical form and turn it into a function pointer. In other words, what I want to do is run:

> ./program a*b

Program turns that into a pointer of a function that returns:

 return a*b;

So, the output of program is

user_defined_function(int)(int)

which would then be part of a much larger program.

I would post some code if I had any idea of how to tackle this problem, but I don't... I just need help with the step of turning the user defined function into a function pointer, since I know how to turn the user defined function into a C function.

Upvotes: 1

Views: 291

Answers (4)

user166390
user166390

Reputation:

Just for fun, here is a link to CINT

CINT is an interpreter for C and C++ code...

... A CINT script can call compiled classes/functions and compiled code can make callbacks to CINT interpreted functions ...

I'm not saying this is a "good" solution (and in fact it may be very "bad" in cases!), but some people have already put a good bit of effort -- "slightly less than 400,000 lines of code" -- into this project ;-)

Happy coding.

Upvotes: 2

Dave
Dave

Reputation: 11162

What you're proposing is entirely possible, you simply write code which transforms user text into machine code. This is called a compiler. gcc would be much like your program, if it ran the code it generated.

Upvotes: 0

David Grayson
David Grayson

Reputation: 87406

This is very hard to do in C because it is a compiled language. You could do what Mario The Spoon is suggesting, or you could switch to a dynamic language like ruby or javascript. These languages have an "eval" method that takes a string and executes the code inside the string, and they have the ability to dynamically define functions.

Upvotes: 1

Mario The Spoon
Mario The Spoon

Reputation: 4859

There is no simple solution to that since you would have to generate code.

Simples solution that comes to my mind for this:

  • generate a C file from within your programm that only has one function, inserting the command line argument as return statement
  • give the function a known or generated name
  • exec the compiler and generate a shared library
  • dynamically load that shared library
  • call the known function

I fear it doesn't get any simpler than that.

The other solution would be to write/ use an expression parser and parse the math expression and than evaluate at runtime...

Upvotes: 2

Related Questions