N-Api&C++ array buffer数据传递预处理

C++侧:

基于N-API的实现示例:
#include <assert.h>
#include "addon_api.h"
#include "stdio.h"

napi_value CArrayBuffSum(napi_env env, napi_callback_info info)
{
    napi_status status;
    const size_t MaxArgExpected = 1;
    napi_value args[MaxArgExpected];
    size_t argc = sizeof(args) / sizeof(napi_value);

    status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    assert(status == napi_ok);
    if (argc < 1)
        napi_throw_error(env, "EINVAL", "Too few arguments");

    napi_value buff = args[0];
    napi_valuetype valuetype;
    status = napi_typeof(env, buff, &valuetype);
    assert(status == napi_ok);

    if (valuetype == napi_object)
    {
        bool isArrayBuff = 0;
        status = napi_is_arraybuffer(env, buff, &isArrayBuff);
        assert(status == napi_ok);

        if (isArrayBuff != true)
            napi_throw_error(env, "EINVAL", "Expected an ArrayBuffer");
    }

    int32_t *buff_data = NULL;
    size_t byte_length = 0;
    int32_t sum = 0;

    napi_get_arraybuffer_info(env, buff, (void **)&buff_data, &byte_length);
    assert(status == napi_ok);

    printf("\nC:  Int32Array size = %d,  (ie: bytes=%d)",
           (int)(byte_length / sizeof(int32_t)), (int)byte_length);
    for (int i = 0; i < byte_length / sizeof(int32_t); ++i)
    {
        sum += *(buff_data + i);
        printf("\nC:  Int32ArrayBuff[%d] = %d", i, *(buff_data + i));
    }

    napi_value rcValue;
    napi_create_int32(env, sum, &rcValue);

    return (rcValue);
}

JS侧:

'use strict'
const myaddon = require('bindings')('mync1');

function test1() {
    const array = new Int32Array(10);

    for (let i = 0; i < 10; ++i)
        array[i] = i * 5;

    const sum = myaddon.ArrayBuffSum(array.buffer);
    console.log();
    console.log(`js: Sum of the array  = ${sum}`);
}

test1();

运行输出:

C:  Int32Array size = 10,  (ie: bytes=40)
C:  Int32ArrayBuff[0] = 0
C:  Int32ArrayBuff[1] = 5
C:  Int32ArrayBuff[2] = 10
C:  Int32ArrayBuff[3] = 15
C:  Int32ArrayBuff[4] = 20
C:  Int32ArrayBuff[5] = 25
C:  Int32ArrayBuff[6] = 30
C:  Int32ArrayBuff[7] = 35
C:  Int32ArrayBuff[8] = 40
C:  Int32ArrayBuff[9] = 45
js: Sum of the array  = 225

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值