简体   繁体   English

将 N-API object 读入 C++ 原语

[英]Reading N-API object into C++ primitive

I've created a simple N-API module starting from the ObjectWrap boilerplate of generator-napi-module, and successfully passed data (an array containing objects with string, number and boolean properties) to JS.我从 generator-napi-module 的 ObjectWrap 样板开始创建了一个简单的 N-API 模块,并成功地将数据(包含具有字符串、数字和 boolean 属性的对象的数组)传递给 JS。 However, I'm unable to parse the properties of one of the same objects passed back to the native code;但是,我无法解析传递回本机代码的同一对象之一的属性; specifically, creating a uint32_t value from a property (a number) of the passed object.具体来说,根据传递的 object 的属性(数字)创建uint32_t值。

Suppose an array of objects is created and passed to JS:假设创建了一个对象数组并将其传递给 JS:

Napi::Value ObjectWrapAddon::GetSomeList(const Napi::CallbackInfo& info){
  Napi::Env env = info.Env();
  native_struct_one *data = NULL;
  native_struct_two opts = { TRUE,FALSE,FALSE };
  int retVal = native_lib_method(&data, &opts);
  if(retVal!=OK) {
    return Napi::Array::New(env); // return empty array
  }
  Napi::Array arr = Napi::Array::New(env);
  uint32_t i = 0;
  do {
    Napi::Object tempObj = Napi::Object::New(env);
    tempObj.Set("someProp", data->someVal);
    arr[i] = tempObj;
    i++;
    data = data->next;
  } while(data);
  return arr;
}

Then one of those objects is passed to a native function call:然后将这些对象之一传递给本机 function 调用:

Napi::Value ObjectWrapAddon::OtherMethod(const Napi::CallbackInfo& info){
  Napi::Env env = info.Env();
  Napi::Object obj = info[0].As<Napi::Object>();
  uint32_t temp = obj.Get("someProp").As<Napi::Number>();
  return Napi::Number::New(env, temp);
}

This builds fine, but the above OtherMethod() gives an A number was expected error at uint32_t temp = obj.Get('someProp').As<Napi::Number>() .这构建得很好,但是上面的 OtherMethod() 在uint32_t temp = obj.Get('someProp').As<Napi::Number>()处给出了一个A number was expected错误。

How would I create a native (C++) value from a JS object property value?如何从 JS object 属性值创建本机 (C++) 值?

I missed two things, which allow this to work:我错过了两件事,这让它起作用:

  1. I was inconsistent with strings when using Get/Set.我在使用 Get/Set 时与字符串不一致。 If Napi::Object::Set is used with single quotes, single quotes must be used with Napi::Object::Get;如果Napi::Object::Set与单引号一起使用,单引号必须与Napi::Object::Get一起使用; likewise for double quotes.双引号也是如此。
  2. Uint32Value() method needs to be used per the docs (I must have removed this in my tinkering), giving: uint32_t temp = obj.Get("someProp").As<Napi::Number>().Uint32Value(); 根据文档需要使用 Uint32Value() 方法(我必须在我的修补中删除它),给出: uint32_t temp = obj.Get("someProp").As<Napi::Number>().Uint32Value();

Fixing these issues provides the expected behavior and output.修复这些问题提供了预期的行为和 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM