[erlang-questions] using strings with NIF

Zoltan Lajos Kis kiszl@REDACTED
Wed Dec 9 08:51:24 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)
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>
>

Hi Jason,

You seem to be mixing up the C API of NIF and Erl_Interface there. My
guess is that this is not possible, as apparently NIF's use ERL_NIF_TERM
while Erl_Interface uses ETERM for Erlang terms. I can be wrong though; if
that's the case, throw an RTFM at me :-).

Regarding strings, the best choice is to allocate a char*, and then
iterate over your Erlang list with enif_get_list_cell, copying each char
(i.e. int) one by one.

Regards,
Zoltan.



More information about the erlang-questions mailing list