我有 C++ 源库,我想在我的 Node.js 应用程序中使用它。为了了解它是如何工作的,我使用 node-gyp 来编译 C++ 代码,它有 2 个用于计算校验和的简单函数(crc16 和 crc16Two)。
void crc16(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.Length() < 2) {
// Throw an Error that is passed back to JavaScript
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
uint32_t size = args[1]->Uint32Value();
Local<Array> *data;
Local<Array> jsArray = Local<Array>::Cast(args[0]);
*data = jsArray;
uint16_t crc = 0xFFFF;
uint8_t i = 0;
while (size--)
{
crc ^= data++ << 8;
for (i = 0; i < 8; i++)
crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;
}
Local<Number> num = Number::New(isolate, crc);
args.GetReturnValue().Set(num);
}
void crc16Two(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
// Check the number of arguments passed.
if (args.Length() < 2) {
// Throw an Error that is passed back to JavaScript
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
// Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
// Perform the operation
uint16_t v1 = args[0]->Uint32Value();
uint16_t v2 = args[1]->Uint32Value();
uint16_t crc = 0xFFFF;
uint8_t i = 0;
crc ^= v1 << 8;
for (i = 0; i < 8; i++)
crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;
crc ^= v2 << 8;
for (i = 0; i < 8; i++)
crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;
Local<Number> num = Number::New(isolate, crc);
args.GetReturnValue().Set(num);
}
Crc16Two 工作正常,我得到了正确的结果,但是当我用 node-gyp rebuild
编译 crc16 时我有错误:
..\Crc.c (49): error C2296: <<: inadmissible, the left operand is "v8::Local <v8 :: Array> *" [C:\Users\dns\Desktop\Crc\build\addon.vcxproj]
这里绑定(bind).gyp:
{ "targets": [{"target_name": "addon", "sources": [ "crc.cc" ], "include_dirs" : ["<!(node -e \"require('nan')\")"]}]}
以及 Node.js 上的代码:
var addon = require('bindings')('addon');
var buf = new Buffer([0,1,2,3,4,5,6,7,8,9]);
console.log(addon.crc16(buf,10));
console.log(addon.crc16Two(32145, 1470));
能告诉我怎么解决吗?我想我做错了什么。
最佳答案
我对这一行很困惑:
crc ^= data++ << 8;
数据实际上是:
v8::Local <v8 :: Array> *
但是来自documentation ,没有提到 << 运算符实现。这个错误对我来说是合理的。位移看起来很奇怪,你真的确定要这样做吗?
此外,您所做的就在上面:
Local<Array> *data;
Local<Array> jsArray = Local<Array>::Cast(args[0]);
*data = jsArray;
在你写 *data = jsArray 的那一刻,数据是一个未初始化的指针,写 *data 会让你的程序崩溃。
关于javascript - 使用 node-gyp 在 node.js 中转换数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089167/