【发布时间】:2020-12-21 22:56:56
【问题描述】:
我能够执行一个 hello world 示例,但除此之外,我还是 nan 和 node add-ons 的新手。
-
我担心内存泄漏,所以如果我造成任何问题,请告诉我 知道。
-
我如何将一个数组推送到
out数组上,类似于[].push([0, 1])。如果可能的话,我不确定如何在不创建新变量来存储它的情况下以最干净的方式进行操作。 -
另外,如果我正在做的其他事情不是最佳做法,请告诉我!我已经研究了一段时间了。
这是我目前的代码
#include <nan.h>
void Method(const Nan::FunctionCallbackInfo <v8::Value> &info) {
v8::Local <v8::Context> context = info.GetIsolate()->GetCurrentContext();
v8::Local <v8::Array> coordinate = v8::Local<v8::Array>::Cast(info[0]);
unsigned int radius = info[2]->Uint32Value(context).FromJust();
// Also if creating the array is wasteful this way by giving it the max possible size
v8::Local <v8::Array> out = Nan::New<v8::Array>(x * y);
for (int x = -radius; x <= radius; ++x) {
for (int y = -radius; y <= radius; ++y) {
if (x * x + y * y <= radius * radius) {
// I need to push something like [x + coordinate->Get(context, 0), y + coordinate->Get(context, 0)];
out->push_back();
}
}
}
}
我后来能够写这个。如果有人能指出我是否正确接近它和/或是否有任何内存问题我需要注意。
#include <nan.h>
void Method(const Nan::FunctionCallbackInfo <v8::Value> &info) {
v8::Local <v8::Context> context = info.GetIsolate()->GetCurrentContext();
v8::Local <v8::Array> coordinates v8::Local<v8::Array>::Cast(info[0]);
int radius = info[1]->Int32Value(context).FromJust();
v8::Local <v8::Array> out = Nan::New<v8::Array>();
int index = 0;
for (unsigned int i = 0; i < coordinates->Length(); i++) {
v8::Local <v8::Array> coordinate = v8::Local<v8::Array>::Cast(coordinates->Get(context, i).ToLocalChecked());
int xArg = coordinate->Get(context, 0).ToLocalChecked()->Int32Value(context).FromJust();
int yArg = coordinate->Get(context, 1).ToLocalChecked()->Int32Value(context).FromJust();
for (int xPos = -radius; xPos <= radius; ++xPos) {
for (int yPos = -radius; yPos <= radius; ++yPos) {
if (xPos * xPos + yPos * yPos <= radius * radius) {
v8::Local <v8::Array> xy = Nan::New<v8::Array>();
(void) xy->Set(context, 0, Nan::New(xPos + xArg));
(void) xy->Set(context, 1, Nan::New(yPos + yArg));
(void) out->Set(context, index++, xy);
}
}
}
}
info.GetReturnValue().Set(out);
}
【问题讨论】:
-
对不起,为什么标签是
node.js? -
这是使用 npm "nan" 包添加的节点 js 代码,np!
-
哦,好吧,对不起,只是混淆了。
标签: node.js node.js-addon