我正在尝试将V8::AddMemoryAllocationCallback方法用于NodeJS C ++插件。我想调用该方法并返回该大小值。我提出了以下代码。似乎是它没有调用回调方法。 代码来自goingnative npm模块。
但是memCallback
方法没有触发。为什么?怎么解决?
它将使用以下C ++代码访问V8库。
//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用于构建和运行代码(从当前文件夹尝试node-gyp rebuild && node index.js 1000 && ls /tmp/
)
//binding.gyp
{
"targets": [
{
"target_name": "myaddon",
"sources": [ "myaddon.cc" ],
"include_dirs": [ "<!(node -e \"require('nan')\")" ]
}
]
}
以下是JavaScript代码。我创建了一些变量来分配一些内存。
//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");
当前输出是;
X: 0 Y: 0
Done!
X: 0 Y: 1
Done!
X: 0 Y: 2
Done!
X: 0 Y: 3
Done!
X: 0 Y: 4
Done!
X: 0 Y: 5
Done!
X: 0 Y: 6
Done!
X: 0 Y: 7
Done!
X: 0 Y: 8
Done!
X: 0 Y: 9
Done!
The End
答案 0 :(得分:2)
使用限制较少的通知设置可能有所帮助(kObjectSpaceAll
而不是kObjectSpaceNewSpace
和/或kAllocationActionAll
而非kAllocationActionAllocate
。
要将size
传递给您的回调,可以采取以下几种方式:
首先,您可能会考虑使用EventEmitter而不是回调,因为memCallback
将被多次调用,除非您真的只希望为下一次memCallback
调用触发回调。使用EventEmitter解决方案,您只需在C ++域中注册一次JS回调,它将全局存储并在memCallback
内调用。然后在JS land中,你只需在执行JS回调时发出一个事件。
你甚至可以调整它,以便JS回调(甚至可能是C ++回调)只在你的事件有监听器时才在C ++域中注册(EventEmitter提供事件来通知你何时为事件添加和删除监听器)。这可能有助于提高绩效。
如果你真的想要使用多次执行的回调(这实际上违背了节点社区的一般期望),那么你必须将JS回调存储在某种全局C ++数组结构中和提供了一些方法来取消注册&#34; JS回调所以它们不再被调用(将从C ++数组中删除JS回调)。