From 89a1d919117a6c442b955cd370f08b1c30105e6a Mon Sep 17 00:00:00 2001 From: Josh Nussbaum Date: Mon, 21 Sep 2015 19:13:30 -0400 Subject: [PATCH] Added dynamic calling in ffi_nif --- c_src/ffi_nif.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/c_src/ffi_nif.c b/c_src/ffi_nif.c index 9bdbb18..798c8bc 100644 --- a/c_src/ffi_nif.c +++ b/c_src/ffi_nif.c @@ -2,6 +2,7 @@ #include #include #include +#include #define MAXLEN 1024 @@ -11,13 +12,29 @@ enum { INT } TYPE; -static void call(int argc, ffi_type **args, void **values, ffi_type* returnType) { +static void call(char *library, char *function, int argc, ffi_type **args, void **values, ffi_type* returnType) { ffi_cif cif; int returnValue; + void* handle; + void* (*fn); + + handle = dlopen(library, RTLD_LAZY); + + if (!handle) { + return; + } + + fn = dlsym(handle, function); + + if (dlerror() != NULL) { + return; + } if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argc, returnType, args) == FFI_OK) { - ffi_call(&cif, (void*)puts, &returnValue, values); + ffi_call(&cif, (void*)fn, &returnValue, values); } + + dlclose(handle); } static ERL_NIF_TERM nif_call(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) @@ -120,11 +137,9 @@ static ERL_NIF_TERM nif_call(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[] break; } - printf("%s.%s() %d %d\n", library, function, argumentsLength, returnType); + call(library, function, argumentsLength, ffiArgs, ffiValues, ffiReturnType); - call(argumentsLength, ffiArgs, ffiValues, ffiReturnType); - - returnValue = 100; + returnValue = 1; return enif_make_int(env, returnValue); }