Skip to content

Instantly share code, notes, and snippets.

@leeavital
Last active August 29, 2015 14:18
Show Gist options
  • Save leeavital/83474c16acc619af1204 to your computer and use it in GitHub Desktop.
Save leeavital/83474c16acc619af1204 to your computer and use it in GitHub Desktop.
DSO FFI
fun naiveIsPrime n =
let
fun helper n agg =
if agg = 1 then
true
else if n mod agg = 0 then
false
else
helper n (agg - 1)
in
helper n (n-1)
end
fun naivePrims n =
let fun helper n x =
if n = 0 then
[]
else if (naiveIsPrime x) then
x::(helper (n-1) (x+1))
else
helper (n-1) (x+1)
in
helper n 2
end
exception NoArgs
(*
val n = case CommandLine.arguments () of
(x::nil) => Option.valOf (Int.fromString(x))
| _ => raise NoArgs
val ns = naivePrims n
val _ = List.app (print o (fn x => x ^ ",") o Int.toString) ns
*)
val e = _export "naiveIsPrime": (int -> bool) -> unit;
val _ = e naiveIsPrime
(* val driver = _import "driver" public: unit -> unit;
val _ = driver () *)
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main () {
printf("hello world\n");
void* lib_handle = dlopen("domath.dylib", RTLD_LOCAL|RTLD_LAZY);
if (!lib_handle) {
printf("[%s] Unable to load library: %s\n", __FILE__, dlerror());
exit(EXIT_FAILURE);
}
printf("loaded handle\n");
// bool (*naiveIsPrime)(int) = dlsym(lib_handle, "_naiveIsPrime");
void (*domath_open)(void) = dlsym(lib_handle, "domath_open");
if (!domath_open) { // addRating is guaranteed to exist in libRatings.A.dylib
printf("[%s] Unable to get symbol: %s\n", __FILE__, dlerror());
exit(EXIT_FAILURE);
}
printf("loaded domath_open\n");
printf("init sml runtime\n");
domath_open();
printf("done!\n");
bool (*isPrime)(int) = dlsym(lib_handle, "naiveIsPrime");
if (!isPrime) { // addRating is guaranteed to exist in libRatings.A.dylib
printf("[%s] Unable to get symbol: %s\n", __FILE__, dlerror());
exit(EXIT_FAILURE);
}
printf("answer: %d\n", isPrime(4));
}
# -verbose 3 flag is ommited
$ ./build/bin/mlton -codegen llvm -default-ann 'allowFFI true' -link-opt -fPIC -format library domath.sml
# on linux: relocation R_X86_64_32 against `CReturnP' can not be used when making a shared object; recompile with -fPIC
# on OSX: no problem
$ gcc hello.c
$ ./a.out
hello world
loaded handle
loaded domath_open
init sml runtime
zsh: segmentation fault ./a.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment