dynamic.c 1.2 KB
Newer Older
B
Ben 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/* Compile with:
LDLIBS="-lm -ldl -lreadline" CFLAGS="-g -Wall -std=gnu11 -O3" make dynamic
*/
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>

void get_a_function(){
    FILE *f = fopen("fn.c", "w");
    fprintf(f, "#include <math.h>\n"
               "double fn(double in){\n");
    char *a_line = NULL;
B
Ben 已提交
14
    char *prompt = ">>double fn(double in){\n>> ";
B
Ben 已提交
15 16
    do {
        free(a_line);
B
Ben 已提交
17
        a_line = readline(prompt);
B
Ben 已提交
18
        fprintf(f, "%s\n", a_line);
B
Ben 已提交
19
        prompt = ">> ";
B
Ben 已提交
20 21 22 23 24
    } while (strcmp(a_line, "}"));
    fclose(f);
}

void compile_and_run(){
B
Ben 已提交
25
    if (system("c99 -fPIC -shared fn.c -o fn.so")!=0){
B
Ben 已提交
26 27 28 29
        printf("Compilation error.");
        return;
    }

30
    void *handle = dlopen("./fn.so", RTLD_LAZY);
B
Ben 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    if (!handle) printf("Failed to load fn.so: %s\n", dlerror());

    typedef double (*fn_type)(double);
    fn_type f = dlsym(handle, "fn");
    printf("f(1) = %g\n", f(1));
    printf("f(2) = %g\n", f(2));
    printf("f(10) = %g\n", f(10));
}

int main(){
    printf("I am about to run a function. But first, you have to write it for me.\n"
        "Enter the function body. Conclude with a '}' alone on a line.\n\n");
    get_a_function();
    compile_and_run();
}