问题
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?
来源:https://stackoverflow.com/questions/33423828/erlang-pass-an-nif-object-between-functions