-
Notifications
You must be signed in to change notification settings - Fork 2
/
embedding.cpp
65 lines (40 loc) · 1.65 KB
/
embedding.cpp
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
#include <iostream>
#include <julia.h>
int main(int argc, char* argv[]) {
static const int N = 10;
double a[N];
/* required: setup the Julia context */
jl_init(JULIA_INIT_DIR);
//////////// Usual stuff
/* run Julia commands */
jl_eval_string("println(sqrt(2.0))");
jl_value_t* array_type = jl_apply_array_type(jl_float64_type, 1);
jl_array_t* a_jl = jl_ptr_to_array_1d(array_type, a, N, 0);
jl_eval_string("function g(a) \n a[:] = 1:length(a) \nend");
jl_call1(jl_get_function(jl_main_module, "g"), (jl_value_t*)a_jl);
jl_eval_string("f(x) = x .^ 2");
jl_function_t* func = jl_get_function(jl_main_module, "f");
for (int i = 0; i < N; ++i) {
double ret = jl_unbox_float64(jl_call1(func, jl_box_float64(a[i])));
std::cout << ret << std::endl;
}
std::cout << std::endl;
//////////// Getting a native function pointer to a Julia function
jl_eval_string("f(x::Int)::Int = 2x");
int (*f)(int) = (int (*)(int))(jl_unbox_voidpointer(jl_eval_string("cfunction(f, Int, (Int,))")));
std::cout << "This is really nice! " << f(123) << std::endl;
// jl_eval_string("@code_native f(123)");
// jl_eval_string("this_function_does_not_exist()");
if (jl_exception_occurred()) {
jl_show(jl_stderr_obj(), jl_exception_occurred());
jl_printf(jl_stderr_stream(), "\n");
}
/* strongly recommended: notify Julia that the
program is about to terminate. this allows
Julia time to cleanup pending write requests
and run all finalizers
*/
jl_atexit_hook(0);
std::cout << " ... Ok ... " << std::endl;
return 0;
}