Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <dlfcn.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdint.h>
- #include <inttypes.h>
- #include <sys/wait.h>
- void compile_func_file(char * function) {
- const char scriptName[] = "func.c";
- int f = open(scriptName, O_WRONLY | O_TRUNC | O_CREAT, 0666);
- char begin[] =
- "#include <math.h>\n"
- "double f(double x) {\n"
- " return ";
- write(f, begin, strlen(begin));
- write(f, function, strlen(function));
- char end[] =
- ";\n"
- "}";
- write(f, end, sizeof(end) - 1);
- close(f);
- if (fork() == 0) {
- execlp("gcc", "gcc", scriptName, "-lm", "-c", "-o", "func.o", "-fPIC", NULL);
- _exit(1);
- }
- wait(NULL);
- if (fork() == 0) {
- execlp("gcc", "gcc", scriptName, "-lm", "-shared", "-o", "func.so", NULL);
- _exit(1);
- }
- wait(NULL);
- }
- int main(int argc, char *argv[]) {
- compile_func_file(argv[4]);
- void *handle = dlopen("./func.so", RTLD_LAZY);
- void *sym = dlsym(handle, "f");
- double left = strtod(argv[1], NULL), right = strtod(argv[2], NULL);
- long long n = strtoll(argv[3], NULL, 10);
- double dx = (right - left) / n;
- double sum = 0;
- for (long long i = 0; i < n; ++i) {
- double xi = left + i * dx;
- sum += ((double (*)(double)) sym)(xi) * dx;
- }
- dlclose(handle);
- printf("%.10g\n", sum);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement