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
I could be wrong, but I would think that
ERL_NIF_TERM enif_make_list(ErlNifEnv* env, unsigned cnt, ...)
is what you want, since in Erlang "strings" are just lists of bytes.
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.
I've put enif_get_string on the ToDo.
Here is a web site in some eastern language that has a
"my_enif_get_string" implemented. I leave it up to you to figure out the
copyrights :-)
http://d.hatena.ne.jp/vostok92/20091201/1259680319
/Sverker, Erlang/OTP Ericsson
This page is written in Japanese and it's about a Tokyo Cabinet client
as NIF.
Kota Uenishi aka kuenishi's yatce is another Tokyo Cabinet client, now
under migration to NIF.
http://bitbucket.org/kuenishi/yatce/wiki/Home
FYI
Kenji Rikitake
(I happen to read Japanese)