Elixir NIF-Hello World example on x64 Mac OSX

Hey. I am trying to get the Hello World example for Erlang NIF (Native Implemented Function) shown here. http://www.erlang.org/doc/man/erl_nif.html for working with Elixir on OSX 64bit.

First I create C code:

/* niftest.c */ #include "erl_nif.h" static ERL_NIF_TERM hello(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { return enif_make_string(env, "Hello world!", ERL_NIF_LATIN1); } static ErlNifFunc nif_funcs[] = { {"hello", 0, hello} }; ERL_NIF_INIT(niftest,nif_funcs,NULL,NULL,NULL,NULL) 

Then I will successfully compile it with gcc for 64-bit architecture, as suggested here by Erlang NIF Test - OS X Lion

 gcc -undefined dynamic_lookup -dynamiclib niftest.c -o niftest.so -I /usr/local/Cellar/erlang/R14B02/lib/erlang/usr/include 

which creates the necessary niftest.so file that I could interact with in Erlang / Elixir. My Elixir (niftest.ex) looks like this (using a more complex example here ):

 defmodule Niftest do @onload :init def init() do :erlang.load_nif("./niftest", 0) :ok end def hello() do "NIF library not loaded" end end 

Now with niftest.so and niftest.ex in the same directory, I run the elixir using iex and type Niftest.hello , and all I return is: "The NIF library is not loaded"

Did I miss a vital step? - please, help!

+8
erlang elixir native macos erlang-nif
source share
1 answer

Library loading fails. You can claim to succeed using:

 :ok = :erlang.load_nif("./niftest", 0) 

This will result in an error:

 ** (MatchError) no match of right hand side value: {:error, {:bad_lib, 'Library module name \'niftest\' does not match calling module \'\'Elixir.Niftest\'\''}} niftest.ex:4: Niftest.init/0 

This is because NIF lib can only be called from its owning module. The name of this module is the first argument of the ERL_NIF_INIT macro, so you can fix this by changing this call and recompiling:

 ERL_NIF_INIT(Elixir.Niftest,nif_funcs,NULL,NULL,NULL,NULL) 

There is also a typo in the load hook. It should be:

 @on_load :init 
+11
source share

All Articles