Skip to content

Instantly share code, notes, and snippets.

@DeedleFake
Created December 12, 2023 19:43
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 DeedleFake/1eff2e08be0748c274ee9848c4999e59 to your computer and use it in GitHub Desktop.
Save DeedleFake/1eff2e08be0748c274ee9848c4999e59 to your computer and use it in GitHub Desktop.
Go/Elixir NIF Experiment

Go/Elixir NIF Experiment

This was a quick little experiment to try to call Go code from Elixir. To try it out, simply run

$ go build -buildmode=c-shared -o nif-test.so
$ iex test.exs

This will put you into an IEx shell in which you can call Test.test/2 to add two integers together via a call to a Go function.

module nif-test
go 1.21.5
#include <erl_nif.h>
extern ERL_NIF_TERM test_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM *argv);
static ErlNifFunc nif_funcs[] = {
{"test", 2, test_nif},
};
ERL_NIF_INIT(Elixir.Test, nif_funcs, NULL, NULL, NULL, NULL)
defmodule Test do
@on_load :init
def init() do
:erlang.load_nif("./nif-test", 0)
end
def test(_, _) do
raise "nif not loaded"
end
end
package main
/*
#cgo CFLAGS: -I/usr/lib/erlang/usr/include
#include <erl_nif.h>
typedef const ERL_NIF_TERM const_ERL_NIF_TERM;
*/
import "C"
import "unsafe"
//export test_nif
func test_nif(env *C.ErlNifEnv, argc C.int, argv *C.const_ERL_NIF_TERM) C.ERL_NIF_TERM {
args := unsafe.Slice(argv, argc)
var a, b C.int
C.enif_get_int(env, args[0], &a)
C.enif_get_int(env, args[1], &b)
return C.enif_make_int(env, a+b)
}
func main() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment