Skip to content

Instantly share code, notes, and snippets.

@mattsan
Created October 14, 2018 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattsan/1d0fc1a02965f19aa53db0eb5cc5376b to your computer and use it in GitHub Desktop.
Save mattsan/1d0fc1a02965f19aa53db0eb5cc5376b to your computer and use it in GitHub Desktop.
NIF in Elixir

Elixir で NIF を利用するサンプル

Erlang の NIF のドキュメントにあるコードを Elixir で利用するようにしたもの。 C のコードはモジュール名を Elixir のモジュール名の形式に変更したのみである。

see http://erlang.org/doc/man/erl_nif.html

$ make
$ iex
iex(1)> c "nif_test.ex"
[NifTest]
iex(2)> NifTest.hello
'Hello world!'
ERL_INCLUDE_PATH=$(shell elixir -e 'IO.puts [:code.root_dir, "/erts-", :erlang.system_info(:version), "/include"]')
CFLAGS=-undefined dynamic_lookup -dynamiclib -I$(ERL_INCLUDE_PATH)
nif_test.so: nif_test.c
gcc $(CFLAGS) -o $@ $^
#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(Elixir.NifTest, nif_funcs, NULL, NULL, NULL, NULL)
defmodule NifTest do
@on_load :init
def init do
:erlang.load_nif("./nif_test", 0)
end
def hello do
"NIF library not loaded"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment