using strings with NIF

Jason Frame jasonwframe@REDACTED
Wed Dec 9 05:08:54 CET 2009


Hi,

I am trying to use a string as an argument with NIF. I can't work out
how to extract the string on the c side though. Using a int is quite
simple with the enif_get_int function but there doesn't seem be a
similar function for strings. I have tried encoding a tuple with
term_to_binary then using erl_decode and then use erl_element and the
associated functions to extract the string. But it fails with a
segfault and I'm sure there is probably a better way to do this.

1> c(niftest).
{ok,niftest}
2> niftest:init().
ok
3> niftest:test().
Segmentation Fault (core dumped)

-module(niftest).
-export([init/0, hello/1, test/0]).
init() ->
      erlang:load_nif("./niftest", 0).
hello(_Value) ->
      "NIF library not loaded".
test() ->
      hello(term_to_binary({"hello"})).

/* niftest.c */
#include "erl_nif.h"
#include "erl_interface.h"
#include "ei.h"

static ERL_NIF_TERM hello(ErlNifEnv* env, ERL_NIF_TERM al)
{
    ErlNifBinary bin;
    ETERM *tuple;

    if (!enif_is_binary(env, al)) {
      return enif_make_badarg(env);
    }

    enif_inspect_binary(env, al, &bin);
    tuple = erl_decode(bin.data); // fails here

    return enif_make_string(env, "dummy value");
}
static ErlNifFunc nif_funcs[] =
{
    {"hello", 1, hello}
};
ERL_NIF_INIT(niftest,nif_funcs,NULL,NULL,NULL,NULL)


More information about the erlang-questions mailing list