Advertisement
Guest User

Untitled

a guest
May 27th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. #include <dlfcn.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9. #include <stdint.h>
  10. #include <inttypes.h>
  11. #include <sys/wait.h>
  12.  
  13. void compile_func_file(char * function) {
  14.     const char scriptName[] = "func.c";
  15.     int f = open(scriptName, O_WRONLY | O_TRUNC | O_CREAT, 0666);
  16.    
  17.     char begin[] =
  18.         "#include <math.h>\n"
  19.         "double f(double x) {\n"
  20.         "    return ";
  21.    
  22.     write(f, begin, strlen(begin));
  23.     write(f, function, strlen(function));
  24.    
  25.     char end[] =
  26.         ";\n"
  27.         "}";
  28.     write(f, end, sizeof(end) - 1);
  29.     close(f);
  30.    
  31.     if (fork() == 0) {
  32.         execlp("gcc", "gcc", scriptName, "-lm", "-c", "-o", "func.o", "-fPIC", NULL);
  33.         _exit(1);
  34.     }
  35.     wait(NULL);
  36.  
  37.     if (fork() == 0) {
  38.         execlp("gcc", "gcc", scriptName, "-lm", "-shared", "-o", "func.so", NULL);
  39.         _exit(1);
  40.     }
  41.     wait(NULL);
  42. }
  43.  
  44. int main(int argc, char *argv[]) {
  45.     compile_func_file(argv[4]);
  46.     void *handle = dlopen("./func.so", RTLD_LAZY);
  47.     void *sym = dlsym(handle, "f");
  48.  
  49.     double left = strtod(argv[1], NULL), right = strtod(argv[2], NULL);
  50.     long long n = strtoll(argv[3], NULL, 10);
  51.     double dx = (right - left) / n;
  52.  
  53.     double sum = 0;
  54.     for (long long i = 0; i < n; ++i) {
  55.         double xi = left + i * dx;
  56.         sum += ((double (*)(double)) sym)(xi) * dx;
  57.     }
  58.     dlclose(handle);    
  59.     printf("%.10g\n", sum);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement