c - 如何使用node.js N-API函数检查napi_number类型的napi_value是整数还是小数,

标签 c node.js n-api node-nan node-native-addon

如何检查napi_number类型的给定napi_value整数还是小数(带小数的数字) value)通过使用node.js native N-API函数。 看起来 N-API 中没有 isInt() 或 isDouble() 等效函数(我们也不想使用 V8 函数调用)。让我们考虑这样一个场景:我们通过传递 JavaScript 对象作为参数来从 JavaScript 调用 native 插件函数 f1(),如代码片段所示。

let obj = { n1: 123, n2: 123.45 };
myaddon.f1( obj );

native 函数 f1() 希望通过调用最佳拟合值提取 N- 来提取与键 n1n2 关联的值API函数。例如,要提取 n1 的值,最好使用 napi_get_value_int* 之一,类似地,对于 n2double

napi_get_value_double
napi_get_value_int32
napi_get_value_uint32
napi_get_value_int64

不幸的是,我找不到任何 N-API 函数来验证 napi_number 属性的导数。您遇到过类似的情况吗?如果遇到过,您是如何解决的?

https://nodejs.org/api/n-api.html

最佳答案

已向 node-addon-api 团队提出了有关此功能的请求,他们提供了听起来合乎逻辑的答案。我想与这个社区分享答案,这可能有助于其他人可能有的类似疑问。 Here is the answer from node-addon-api team

While handling numbers with JavaScript, it is important to know that all numbers in JavaScript are double-precision 64 bit IEEE 754 values (despite some engines like v8 might have additional represents on small integers, there is no such definition in ECMA spec and no way to determine these types of number in JavaScript).

napi_get_value_{double,int32,uint32,int64} just convert these value to its desired one. There might be a precision loss in the conversion. If a determined number is required in the case, use BigInt instead.

关于c - 如何使用node.js N-API函数检查napi_number类型的napi_value是整数还是小数,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586425/

相关文章:

c - 在 for 循环内声明变量; c2000编译器出现错误

node.js - 如何异步使用 node-addon-api 的 AsyncContext

c++ - Mac 中 Electron 中的 native C++ 插件出现问题

javascript - Webpack 4从scss中提取css而不是从编译文件中删除sass文件

javascript - 使用node-api将数组缓冲区从C转发到JS

c - 用 C 语言向服务器套接字编程发送各种命令

c++ - 在 C++ 中使 C 函数指针与基于 C 风格堆栈的调用机制一起工作

c - Fwrite 似乎总是追加而不是从游标写入

javascript - 如何在 TypeScript (Node.js) 包中包含全局文件类型声明

javascript - ReactJS 路由器正在覆盖 ExpressJS 路由器