TooTallNate / ref-struct

Create ABI-compliant "struct" instances on top of Buffers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Returning ref to struct from C

robgrimball opened this issue · comments

Nate,

First, thanks for fixing that bug earlier and for the fix to my code too.

I've moved past that successfully and the C function is being called and getting the info from nodejs that it is expecting, my next problem is in getting the result data. It is basically a pointer to a struct that is the start of a null terminated linked list.

The problem seems to be that buff.deref() is attempting to dereference the full struct and all substructs rather than just the full struct. An example is below..

First, the C code :

    struct simple_i {
        int testa;
        int testb;
        struct simple_i * next;
    };

    typedef struct simple_i simple_info;

    simple_info * do_simple_stub() {
        simple_info * si = malloc(sizeof(simple_info));

        si->testa = 1;
        si->testb = 2;
        si->next= NULL;

        return si;
    }

As you can see, this is basically just a simple linked list with two integers and a pointer to the next in the list. The do_simple_stub() function just creates a single element linked list by setting next to NULL.

Now for the nodejs code :

        var SimpleInfo = ref_struct();

        SimpleInfo.defineProperty('testa', ref.types.int);
        SimpleInfo.defineProperty('testb', ref.types.int);
        SimpleInfo.defineProperty('next', ref.refType(SimpleInfo));

        var libsnmp_lib = ffi.Library('libsnmp_lib', {
            'do_simple_stub':[ref.refType(SimpleInfo), []]
        });

        var simpleInfoRef = libsnmp_lib.do_simple_stub();

        var simpleInfo = simpleInfoRef.deref();

This code segfaults when run because next is NULL and I believe simpleInfoRef.deref() is attempting to dereference the 'next' field within the simpleInfoRef. Most linked lists however have NULL as the termination of the linked list, so doing this is problematic.

What I want to do of course eventually is be able to get a linked list's first element returned from a function and be able to walk down that list in nodejs until I reach null.

Any suggestions or help as to how to accomplish this would be greatly appreciated.

Thanks!

Rob