How to use NIFs

Hey guys. Sorry for the silly question but just wanna know if there’s an official guide for using NIFs to call C libraries from Elixir.

Many thanks in advance!

2 Likes

Hello,
You can look at erlang NIF example Erlang NIF
Here’s how you create a Elixir NIF module

defmodule Example do
  @on_load :init

  def init do
    ok = :erlang.load_nif("./complex6_nif", 0).
  end
  # The functions below should be be exported from the NIF. Refer the documentation.
  def foo(_x), do: exit(:nif_not_loaded)

  def bar(_y), do: exit(:nif_not_loaded)

end
2 Likes

For calling C libraries, you may also want to check out Zigler which allows inline nif creation with Zig.

I know this is over a year later, but for those who also have this question, I wrote a bit more in-depth about this specific use case of using NIFs to write bindings to external libraries:

4 Likes

I like blog posts by Andrea Leopardi and one of them is about NIFs in C.

4 Likes