5

I write a C nif code and in function new, it creates a stack struct with enif_alloc_resource and returns that. when i use function enif_make_resources, it always returns <<>> in erlang.

Here is my C code:

#include "erl_nif.h"


static ErlNifResourceType *MEM_RESOURCE;



typedef struct
{
    int n;
    int ps;
    int pe;
    ERL_NIF_TERM *data;
} Stack;



Stack *new(ErlNifEnv *env, int size)
{
    Stack *s = (Stack*) enif_alloc_resource(MEM_RESOURCE, sizeof(Stack));
    s->n = size;
    s->ps = 0;
    s->pe = size - 1;
    s->data = enif_alloc(sizeof(ERL_NIF_TERM) * size);
    return s;
}



static ERL_NIF_TERM new_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    int size;
    if (!enif_get_int(env, argv[0], &size))
        return enif_make_badarg(env);

    Stack *stack = new(env, size);
    ERL_NIF_TERM res = enif_make_resource(env, stack);
    enif_release_resource(stack);

    return res;
}


static ErlNifFunc nif_funcs[] =
{
    {"new", 1, new_nif}
};

static void cleanup(ErlNifEnv *env, void *obj){}

static int load(ErlNifEnv *env, void **priv_data, ERL_NIF_TERM load_info){
    MEM_RESOURCE = enif_open_resource_type(env, NULL, "mem_resource", &cleanup, ERL_NIF_RT_CREATE, 0);
    if (MEM_RESOURCE == NULL)
        return -1;
    return 0;
}

ERL_NIF_INIT(q4, nif_funcs, load, NULL, NULL, NULL)

Now the function new_nif always returns <<>> but i checked res is not NULL!. What is the problem?

Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
Amin
  • 755
  • 6
  • 21
  • 1
    There is no problem; in Erlang, resources always look like an empty binary because it's opaque. – Steve Vinoski Oct 29 '15 at 20:25
  • So how can send this object to erlang and pass it to another function? – Amin Oct 29 '15 at 20:30
  • You call your NIF, and it returns a resource object. You store that into a variable, and you later pass it to another call. For example, see the init/update/final groups of functions in [my `erlsha2` library](https://github.com/vinoski/erlsha2). – Steve Vinoski Oct 29 '15 at 20:50

0 Answers0