From 9d0e21a8100d9b5c989b77fbe4add4113927ba49 Mon Sep 17 00:00:00 2001 From: Josh Nussbaum Date: Mon, 21 Sep 2015 18:51:26 -0400 Subject: [PATCH] Added typemap and type sanitizing --- lib/ffi.ex | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/lib/ffi.ex b/lib/ffi.ex index baf526c..a0ad037 100644 --- a/lib/ffi.ex +++ b/lib/ffi.ex @@ -1,14 +1,34 @@ defmodule FFI do @on_load :init + @typemap %{ + void: 0, + string: 1, + int: 2 + } + def init do - :erlang.load_nif("./ffi_nif", 0) + :ok = :erlang.load_nif("./ffi_nif", 0) end - def call({library, name, arguments, return_type}, params), - do: nif_call(library, name, arguments, return_type, params) + def call({library, function, arguments, return_type}, values) do + nif_call(String.to_atom(library), + function, + Enum.map(arguments, &map_type/1), + map_type(return_type), + clean_values(values)) + end - def nif_call(library, name, arguments, return_type, params) do + def nif_call(library, function, arguments, return_type, values) do :badarg end + + defp map_type(type), do: @typemap[type] + + defp clean_values(values) do + Enum.map values, fn + str when is_bitstring(str) -> to_char_list(str) + other -> other + end + end end