zombiecong
2/2/2018 - 7:31 AM

nif_test.cpp

#include "nifpp.h"
#include <functional>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-field-initializers"
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma clang diagnostic ignored "-Wreturn-type"

using namespace nifpp;



class Example{
public:
    Example(ErlNifPid pid,std::function<void(int,ErlNifPid,ErlNifEnv*)> listener){ 
        this->pid_ = pid;
        this->listener_ = listener;
        this->id = 1;

    }
    ~Example(){}


    void test(ErlNifEnv* env){
        listener_(1,this->pid_,env);
    }


    int id;
    std::function<void(int,ErlNifPid,ErlNifEnv*)> listener_;
    ErlNifPid pid_;
};


extern "C" {

    ErlNifResourceType* RES_TYPE;
    ERL_NIF_TERM atom_ok;

    void
    free_res(ErlNifEnv* env, void* obj)
    {

    }


    static int
    load(ErlNifEnv* env, void** priv, ERL_NIF_TERM load_info)
    {

        register_resource<Example>(env, nullptr, "Example");

        atom_ok = enif_make_atom(env, "ok");

        return 0;
    }

    static ERL_NIF_TERM create(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){

        // auto listern = new 
        ErlNifPid pid;



        if(!enif_is_pid(env, argv[0]))
        {
            return enif_make_badarg(env);
        }

        if(!enif_get_local_pid(env, argv[0], &pid))
        {
            return enif_make_badarg(env);
        }


        auto gl = [](int a,ErlNifPid p,ErlNifEnv* en){
            ErlNifEnv* msg_env;


            msg_env = enif_alloc_env();

            enif_send(en, &p, msg_env, atom_ok);
            
            enif_free(msg_env);
            
        };

        auto ret = construct_resource<Example>(pid,gl);

        return make(env,ret);
    }

    static ERL_NIF_TERM
    add(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){
       
    }

    static ERL_NIF_TERM
    read(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){
       

    }

    static ERL_NIF_TERM
    cb(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){
        resource_ptr<Example> ptr;
        get(env,argv[0],ptr);
        // e->test(env);   
    }



    static ErlNifFunc funcs[] = {
        {"create",1,create},
        {"add",1,add},
        {"read",1,read},
        {"cb",1,cb},
    };


    ERL_NIF_INIT(nif_test, funcs, load, NULL, NULL, NULL)

}