Skip to content

Instantly share code, notes, and snippets.

@jvkersch
Created December 6, 2018 09:22
Show Gist options
  • Save jvkersch/f149e130842ec89ad11b807163223179 to your computer and use it in GitHub Desktop.
Save jvkersch/f149e130842ec89ad11b807163223179 to your computer and use it in GitHub Desktop.
Adapted from https://github.com/JuliaLang/PackageCompiler.jl/issues/144.
Compile the C code with
gcc runjl.c -o runjl -Wall -std=gnu99 -I'/Applications/Julia-1.0.app/Contents/Resources/julia/include/julia' -DJULIA_ENABLE_THREADING=1 -fPIC -L'/Applications/Julia-1.0.app/Contents/Resources/julia/lib' -Wl,-rpath,'/Applications/Julia-1.0.app/Contents/Resources/julia/lib' -Wl,-rpath,'/Applications/Julia-1.0.app/Contents/Resources/julia/lib/julia' -ljulia
Use PackageCompiler.jl to produce a shared library from the Julia file.
Base.@ccallable function my_add(x::Cint, y::Cint)::Cint
return x + y
end
#include <dlfcn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <julia.h>
int main()
{
void *handle;
int64_t (*my_add)(int64_t, int64_t);
struct timespec ts0, ts1;
int i = 0;
jl_init_with_image(NULL, "builddir/fun.dylib");
if ((handle = dlopen("builddir/fun.dylib", RTLD_LOCAL)) == NULL) {
goto error;
}
if ((my_add = dlsym(handle, "my_add")) == NULL) {
goto error;
}
clock_t begin, end;
begin = clock();
for (; i < 10000000; i++) {
(*my_add)(5, 6);
}
end = clock();
printf("%f\n", (double)(end - begin) / CLOCKS_PER_SEC);
printf("5 + 6 = %lld\n", (*my_add)(5, 6));
return 0;
error:
fprintf(stderr, "Error: %s\n", dlerror());
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment