Search code examples
cnode.jsnode-ffi

Node-ffi calling c DLL returning a pointer


I'm trying a simple code to test if I know to return a pointer from a C DLL to be used in other functions of the DLL as a parameter. But something doesn't run

C DLL code

#include <stdint.h>

#if defined(WIN32) || defined(_WIN32)
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif


EXPORT int* init() {
    int *p = (int *)calloc(sizeof(int));
    p[0]=33;
    return p;
}


EXPORT int get(int* base) {


  return *base;
}

Code of my node application

var ffi = require('ffi');
var ref = require('ref')


var intPtr = ref.refType('int');

var libm = ffi.Library('./miffi', {
    'init': [ intPtr, [ ] ],
    'get': [ 'int', [  intPtr ] ],
});



var idx = libm.init()
console.log("I get id" )

console.log(libm.get(idx))

But doesn't show the first "console.log", although it doen't show any error. If I remove the line "p[0]=33;" I can see the first "console.log" although get doesn't run.

Thanks a lot


Solution

  • I solved it. I just forgot to add

    #include <stdlib.h>
    

    I didn't see the warning about it.