简体   繁体   中英

Read a line of c code from file and execute in a c program

I have a C program which calculates f(x) for some x values (main.c). I need to get a line of c code from file and that code is my function to execute (function.dot). For example function.dot will contain:

pow((1-x), 0.333);

I need to read this file, get that function and execute in my code (main.c). How can I do that?

Basic steps would be:

  1. Read the line from the file.
  2. Generate a new source file which wraps the line of code inside appropriate code.
  3. Invoke a compiler to compile that code into a shared object/dll.
  4. Load the library.
  5. Call the function in the library.

If the single line of code in the file could be any language, it would be far easier to use something like Lua that can be linked into your main executable.

I will provide some options:

  1. Switch to another interpreted language including python, ruby, perl, ...

    If you are working on small project, I recommend this option.

  2. Implement your own interpreter in C.

    Parse your input, analyze it, execute it. You might find open source implementations: one choice is slang http://www.jedsoft.org/slang/doc/html/slang.html

  3. Call C compiler and dynamically link it.

    It depends on your operating system but system or exec functions help you to call your compiler to handle your input file. If you are using Linux, dlsym can open a shared-object compiled from your input file. You might need to convert your input file into C program. Very slow to compile but fastest to run.

You have several options I can think of: 1) Switch to any number of interpreted langauges (python, perl, etc.) which support this as an easy mechanism. (Example: in python

data = open("function.dot").read()
x = 5
eval(data) #note that this is unsafe if you can't trust data, and you might also need to play with environment

)

2) You could wrap the code in it's own c file... something like (but with more error checking etc... you probably don't want to do this)

void generate_c_program(char *line)
{
  FILE *fp = fopen("myfile.c","wt");
  fprintf(fp,"#include <math.h>\nint main(char *argv, int argc) {\n double x = atof(argv[1]); printf(\"%f\",(%s));}\n");",line); //this is also unsafe if you can't trust data
  fclose(fp);
  //now execute gcc myfile.c
  //now execute a.out
  //optionally cleanup by deleting a.out and myfile.c

}

3) Effectively write your own compiler / parser (which may be fairly easy IF you've done this before and the number of functions / operations you need to support is small or may be a much bigger deal and will rather not fit in this answer)... the extensible way would be to use LEX/YACC or similar)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM