<div dir="ltr"><div dir="ltr">Thu 4 juli 2019 16:11 Max Lapshin <<a href="mailto:max.lapshin@gmail.com">max.lapshin@gmail.com</a>> wrote:<br></div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr"><br><div><br></div><div>I have following code in nif:</div><div><br></div><div>State *s = enif_alloc_resource(..)</div><div>enif_self(env, &s->owner);<br></div><div>ERL_NIF_TERM term = enif_make_resource(env, s);<br>enif_release_resource(s);<br></div><div>return term;</div><div><br></div><div><br></div><div>Then later another thread (not written by me) is calling my callback function:</div><div><br></div><div><br></div><div>void mycallback(void *obj)</div><div>{</div><div>  State *s = obj;</div><div>  ErlNifEnv *msg_env = enif_alloc_env();<br></div><div>  ERL_NIF_TERM term = enif_make_resource(msg_env, s);</div><div>  enif_send(NULL, &s->owner, msg_env, term);</div><div>  enif_free_env(msg_env);</div><div>}</div><div><br></div><div><br></div><div>Is this code correct?</div><div><br></div><div>Should I put release_resource for each make_resource or only for release_resource?</div><div><br></div><div>Is this calling of enif_send correct?</div><div><br></div><div>I'm afraid that I miss these answers in documentation or cannot find them. </div><br></div></blockquote><div><br></div><div>Your code looks good to me. <br></div><div>I only  call enif_release_resource for references obtained by enif_alloc_resource. If you check the documentation for enif_release_resource I think it is pretty clear about this.</div><div>And enif_send looks ok too.</div><div>Maybe you will have a problem if the pid used in the callback is from the same object you allocated in the previous statement, then I do not think that you shall call enif_release_resource at all. And if you only wan't to keep the pid for a callback maybe enif_alloc is enough too?</div><div>  ErlNifPid* pid = (ErlNifPid*) enif_alloc(sizeof(ErlNifPid));<br></div><div>  enif_self(env, pid);</div><div>  ...code to add pid to callback handler..<br></div><div> and do not call enif_free <br></div><div><br></div></div></div>