How to use V8::AddMemoryAllocationCallback method in C++ for a NodeJS Addon

29 views
Skip to first unread message

gihan karunarathne

unread,
Jul 21, 2015, 2:43:38 PM7/21/15
to nod...@googlegroups.com

I'm trying to use V8::AddMemoryAllocationCallback method for a NodeJS C++ Addon. I want to call to that method and return that size value. I came up with following code. Seems to be it's not calling to callback method. The code is taken form goingnative npm module.


But the memCallback method didn't get trigger. Why? How to fix it?


It'll use the following C++ code to access V8 library.


//myaddon.cc
#include <nan.h>
# include <unistd.h>
#include <iostream>
#include <fstream>

using namespace std;
using namespace v8;

static int x = 0;
static int y = 0;

void memCallback(ObjectSpace space, AllocationAction action, int size)   {
    ofstream myfile;
    myfile.open ("/tmp/example.txt");
    myfile << "Writing this to a file.\n";
    myfile.close();

    x = size;
}

NAN_METHOD(Delay) {
  NanScope();

  int delay = args[0].As<Number>()->IntegerValue();
  Local<Function> callback = args[1].As<Function>();

  V8::AddMemoryAllocationCallback(&memCallback, kObjectSpaceNewSpace, kAllocationActionAllocate);

  for(int i = 0; i < 10; i++) {
    y = i;
    Local<Value> argv[] = {NanNew(x), NanNew(y)};
    NanMakeCallback(NanGetCurrentContext()->Global(), callback, 2, argv);
    usleep(delay * 1000);
  }

  NanReturnUndefined();
}

void Init(Handle<Object> exports) {
  exports->Set(NanNew("delay"), NanNew<FunctionTemplate>(Delay)->GetFunction());
}

NODE_MODULE(myaddon, Init)



node-gyp has use to build and run the code (try node-gyp rebuild && node index.js 1000 && ls /tmp/ from current folder)


//binding.gyp
{
  "targets": [
    {
      "target_name": "myaddon",
      "sources": [ "myaddon.cc" ],
      "include_dirs": [ "<!(node -e \"require('nan')\")" ]
    }
  ]
}



Following is the JavaScript code. I have created few variables in order to allocate some memory.


//index.js
var addon = require('bindings')('myaddon')

addon.delay(process.argv[2], function(x, y) {
    console.log("X: ", x, " Y:", y);

    var arr = [], obj = {};
    for (var i = 0; i < 100; i++) {
        arr.push("Text " + i);
    }
    for (var i = 0; i < 100; i++) {
        obj[i] = arr[i];
        delete arr[i];
    }
    console.log('Done!');
})

console.log("The End");
Reply all
Reply to author
Forward
0 new messages