#include <erl_nif.h> #include <string.h> static ERL_NIF_TERM hello(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { const char* greeting = "Здравей от C!"; const size_t greeting_len = strlen(greeting); ERL_NIF_TERM new_binary; unsigned char* new_binary_data = enif_make_new_binary(env, greeting_len, &new_binary); memcpy(new_binary_data, greeting, greeting_len); return new_binary; } static ErlNifFunc nif_funcs[] = { {"hello", 0, hello} }; ERL_NIF_INIT(Elixir.HelloC, nif_funcs, NULL, NULL, NULL, NULL)
(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) -> ERL_NIF_TERM
hello
hello/0
static ErlNifFunc nif_funcs[] = { {"hello", 0, hello} };
ERL_NIF_INIT
defmodule HelloC do @on_load :load_nifs def load_nifs do :ok = :erlang.load_nif("./nif/_build/libhello", 0) end def hello, do: :erlang.nif_error(:nif_not_loaded) end
:erlang.load_nif(<път до библиотеката>, 0)
:ok
@on_load: <function>
@on_load
https://www.erlang.org/doc/man/erl_nif.html
native/<име>/
defp deps do [ {:rustler, "~> 0.28.0"}, ] end
mix deps.get mix rustler.new
#[rustler::nif] fn hello() -> &'static str { "Здравей от Rust!" } rustler::init!("Elixir.HelloRust", [hello]);
use Rustler, ...
defmodule HelloRust do use Rustler, otp_app: :hello_rust, crate: :hello def hello, do: :erlang.nif_error(:nif_not_loaded) end
#[rustler::nif] fn my_func<'a>(env: Env<'a>, arg1: Term<'a>, arg2: Term<'a>) -> Term<'a> { ... }
Env
Term
#[rustler::nif]
ERL_NIF_TERM
env
fn my_func(arg1: Atom, arg2: i32) -> String { ... }
Option
Result
Option - Some(val) -> val - None -> :nil Result - Ok(val) -> {:ok, val} - Err(e) -> {:error, e}
rustler::atoms! { ok, error, unknown_term, foo, bar, baz, }
OwnedEnv
OwnedBinary
load
upgrade
unload
ERL_NIF_INIT(MODULE, nif_funcs, load, NULL, upgrade, unload)
rustler::init!("MODULE", nif_funcs, load = load);
ResourceArc<T>
&T
&mut T
GenServer
Mutex
SpinLock
Mutex::try_lock
Mutex::lock
enif_schedule_nif
env.send
#[rustler::nif(schedule = "DirtyCpu")] pub fn my_lengthy_work() -> i64 { let duration = Duration::from_millis(100); std::thread::sleep(duration); 42 }
rustler::nif