File: embedding.c

package info (click to toggle)
julia 1.0.3%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 49,452 kB
  • sloc: lisp: 236,453; ansic: 55,579; cpp: 25,603; makefile: 1,685; pascal: 1,130; sh: 956; asm: 86; xml: 76
file content (175 lines) | stat: -rw-r--r-- 5,044 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// This file is a part of Julia. License is MIT: https://julialang.org/license

#include <julia.h>
#include <stdio.h>
#include <math.h>

JULIA_DEFINE_FAST_TLS() // only define this once, in an executable

#ifdef _OS_WINDOWS_
__declspec(dllexport) __cdecl
#endif
double my_c_sqrt(double x)
{
    return sqrt(x);
}

jl_value_t *checked_eval_string(const char* code)
{
    jl_value_t *result = jl_eval_string(code);
    if (jl_exception_occurred()) {
        // none of these allocate, so a gc-root (JL_GC_PUSH) is not necessary
        jl_call2(jl_get_function(jl_base_module, "showerror"),
                 jl_stderr_obj(),
                 jl_exception_occurred());
        jl_printf(jl_stderr_stream(), "\n");
        jl_atexit_hook(1);
        exit(1);
    }
    assert(result && "Missing return value but no exception occurred!");
    return result;
}

int main()
{
    jl_init();

    {
        // Simple running of Julia code

        checked_eval_string("println(sqrt(2.0))");
    }

    {
        // Accessing the return value

        jl_value_t *ret = checked_eval_string("sqrt(2.0)");
        double retDouble = jl_unbox_float64(ret);
        printf("sqrt(2.0) in C: %e\n", retDouble);
        fflush(stdout);
    }

    {
        // Same as above but with function handle (more flexible)

        jl_function_t *func = jl_get_function(jl_base_module, "sqrt");
        jl_value_t* argument = jl_box_float64(2.0);
        jl_value_t* ret = jl_call1(func, argument);
        double retDouble = jl_unbox_float64(ret);
        printf("sqrt(2.0) in C: %e\n", retDouble);
        fflush(stdout);
    }

    {
        // 1D arrays

        jl_value_t* array_type = jl_apply_array_type((jl_value_t*)jl_float64_type, 1);
        jl_array_t* x          = jl_alloc_array_1d(array_type, 10);
        // JL_GC_PUSH* is required here to ensure that `x` is not deleted before
        // (aka, is gc-rooted until) the program reaches the corresponding JL_GC_POP()
        JL_GC_PUSH1(&x);

        double* xData = jl_array_data(x);

        size_t i;
        for (i = 0; i < jl_array_len(x); i++)
            xData[i] = i;

        jl_function_t *func  = jl_get_function(jl_base_module, "reverse!");
        jl_call1(func, (jl_value_t*) x);

        printf("x = [");
        for (i = 0; i < jl_array_len(x); i++)
            printf("%e ", xData[i]);
        printf("]\n");
        fflush(stdout);

        JL_GC_POP();
    }

    {
        // Defining a Julia function and calling it

        checked_eval_string("my_func(x) = 2 * x");

        jl_function_t *func = jl_get_function(jl_current_module, "my_func");
        jl_value_t* arg = jl_box_float64(5.0);
        double ret = jl_unbox_float64(jl_call1(func, arg));

        printf("my_func(5.0) = %f\n", ret);
        fflush(stdout);
    }

    {
        // Calling a C function from Julia (from C)

        // in a shared library (exported, by name)
        checked_eval_string("println( ccall(:my_c_sqrt, Float64, (Float64,), 2.0) )");

        // or via a pointer
        jl_value_t *call_by_ptr = checked_eval_string(
                "my_c_sqrt -> println( ccall(my_c_sqrt, Float64, (Float64,), 2.0) )");
        jl_call1(call_by_ptr, jl_box_voidpointer(my_c_sqrt));
    }

    {
        // Handling exceptions gracefully

        jl_value_t *f = checked_eval_string("function this_function_has_no_methods end");
        jl_call0(f);

        if (jl_exception_occurred()) {
            jl_call2(jl_get_function(jl_base_module, "showerror"),
                     jl_stderr_obj(),
                     jl_exception_occurred());
            jl_printf(jl_stderr_stream(), "\n");
        }

    }

    {
        // Creating and using a native C function handle
        // to a Julia function signature

        checked_eval_string(
        "function bar()\n"
        "    println(\"called bar\")\n"
        "    random_return_value = 42\n"
        "end"
        );

        checked_eval_string(
        "function bar_from_c()\n"
        "    bar()\n"
        "    nothing\n"
        "end"
        );

        typedef void (*Func_VOID__VOID)(void);
        jl_value_t *pbar = jl_eval_string("@cfunction(bar_from_c, Cvoid, ())");
        Func_VOID__VOID bar = (Func_VOID__VOID)jl_unbox_voidpointer(pbar);
        bar();
        checked_eval_string("bar() = println(\"calling new bar\")");
        bar();
    }

    {
        // Importing a Julia package

        checked_eval_string(
        "let dir = dirname(unsafe_string(Base.JLOptions().julia_bin))\n"
        // disable the package manager
        "    ENV[\"JULIA_PKGDIR\"] = joinpath(dir, \"disabled\")\n"
        // locate files relative to the "embedding" executable
        "    stdlib = filter(env -> startswith(Base.find_package(Base, \"Distributed\"), env), Base.load_path())[end]\n"
        "    push!(empty!(LOAD_PATH), dir, stdlib)\n"
        "end"
        );
        checked_eval_string("import LocalModule");
        checked_eval_string("LocalModule.myapp()");
    }

    int ret = 0;
    jl_atexit_hook(ret);
    return ret;
}