Search code examples
cjuliaread-eval-print-loop

Julia retrieve global variable in C


I want to retrieve global variable x I just set in Julia from my C application. Here's the code I have so far:

#include <julia.h>

void SimpleExecute(char *command, char *resultVar, char* result) {

    jl_eval_string(command);

    jl_value_t *var = jl_get_global(jl_base_module, jl_symbol(resultVar));

    const char *str = jl_string_ptr(var);

    sprintf(result, "%s", str);
}

int main(int argc, char *argv[])
{
    char* result = malloc(sizeof(char) * 1024);

    jl_init();

    //(void)jl_eval_string("println(sqrt(2.0))"); //works
    (void)SimpleExecute("x=sqrt(2.0)", "x", result);

    jl_atexit_hook(0);
    return 0;
}

However debugger shows that var is still NULL after jl_get_global call. Why? I followed this tutorial but it does not touch on arbitrary variable retrieval. Source code shows similar usage.

enter image description here


Solution

  • I think there are a few things going on here:

    First, you need to use jl_main_module and not jl_base_module.

    Second, you cannot use jl_string_ptr to get the string value of a integer or floating point value. You can either use x=string(sqrt(2.0)) as the command to run, or use jl_unbox_float64 as a function to unbox the value you get back from Julia.

    #include <julia.h>
    #include <stdio.h>
    
    void SimpleExecute(char *command, char *resultVar, const char* result) {
    
        jl_eval_string(command);
    
        jl_value_t *var = jl_get_global(jl_main_module, jl_symbol(resultVar));
    
    
        if (var && jl_is_string(var)) {
            const char * str = jl_string_ptr(var);
            printf("%s\n", str);
        } else {
            const double val = jl_unbox_float64(var);
            printf("%f\n", val);
        }
    }
    
    int main(int argc, char *argv[])
    {
        char* result = malloc(sizeof(char) * 1024);
    
        jl_init();
    
        // (void)jl_eval_string("println(sqrt(2.0))"); //works
        (void)SimpleExecute("x = sqrt(2.0)", "x", result);
    
        jl_atexit_hook(0);
        return 0;
    }
    

    You can run this by modifying the following:

    cc -I/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/include/julia/ -Wl,-rpath,/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/lib/ -L/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/lib/ -ljulia  main.c -o main