Creating a JS API to a C function that takes a pointer to a complex structure


I need to create a JS API to a C driver function of the following form: int myFunc(MyStruct *pStruct);

…where MyStruct is quite a complicated beast, containing a callback function and a linked list of items:

typedef struct ListItem {
    int a;
    int b;
    struct ListItem *pNext;
} ListItem;

typedef struct {
    int a;
    int (*pCallback)(void *);
    void *pCallbackParam;
    ListItem *pList;
} MyStruct;

I’ve looked at the s2o stuff but that seems to be only for the C-struct-to-JS-object direction, whereas I need to handle the JS-object-to-C-struct direction.

What is the best practice for creating JS representations of such complex structures that I can then convert into the required C structure for the driver?


Why not pass it as an opaque void * ?

in JS, it’ll look like this:

let f1 = ffi('void *create_instance()');
let f2 = ffi('int use_instance(void *, int, int)');

let h = f1();  // Now h holds a pointer to your complex structure
f2(h, 11, 22);   // Pass that pointer to your C function
1 Like

Indeed, that’s fine, the complication is that I need the JS function to be able to populate fields in the structure, which will be picked up in C. For instance, it needs to add items to pList, set the value for a, etc.

What I’ve decided to do so far is create C functions which JS can call to populate the structures, in other words do all the populating over in C where I have the most flexibility. Just not sure if I’m missing a trick by knife-and-forking it in this way.

[EDIT] I think that’s probably what you intend with your f2(), so I guess the approach I’m taking is the appropriate one.

1 Like

Yeah, apparently. Thank you!