当前位置:   article > 正文

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

napi_get_arraybuffer_info

C++侧:

基于N-API的实现示例:
  1. #include <assert.h>
  2. #include "addon_api.h"
  3. #include "stdio.h"
  4. napi_value CArrayBuffSum(napi_env env, napi_callback_info info)
  5. {
  6. napi_status status;
  7. const size_t MaxArgExpected = 1;
  8. napi_value args[MaxArgExpected];
  9. size_t argc = sizeof(args) / sizeof(napi_value);
  10. status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
  11. assert(status == napi_ok);
  12. if (argc < 1)
  13. napi_throw_error(env, "EINVAL", "Too few arguments");
  14. napi_value buff = args[0];
  15. napi_valuetype valuetype;
  16. status = napi_typeof(env, buff, &valuetype);
  17. assert(status == napi_ok);
  18. if (valuetype == napi_object)
  19. {
  20. bool isArrayBuff = 0;
  21. status = napi_is_arraybuffer(env, buff, &isArrayBuff);
  22. assert(status == napi_ok);
  23. if (isArrayBuff != true)
  24. napi_throw_error(env, "EINVAL", "Expected an ArrayBuffer");
  25. }
  26. int32_t *buff_data = NULL;
  27. size_t byte_length = 0;
  28. int32_t sum = 0;
  29. napi_get_arraybuffer_info(env, buff, (void **)&buff_data, &byte_length);
  30. assert(status == napi_ok);
  31. printf("\nC: Int32Array size = %d, (ie: bytes=%d)",
  32. (int)(byte_length / sizeof(int32_t)), (int)byte_length);
  33. for (int i = 0; i < byte_length / sizeof(int32_t); ++i)
  34. {
  35. sum += *(buff_data + i);
  36. printf("\nC: Int32ArrayBuff[%d] = %d", i, *(buff_data + i));
  37. }
  38. napi_value rcValue;
  39. napi_create_int32(env, sum, &rcValue);
  40. return (rcValue);
  41. }

JS侧:

  1. 'use strict'
  2. const myaddon = require('bindings')('mync1');
  3. function test1() {
  4. const array = new Int32Array(10);
  5. for (let i = 0; i < 10; ++i)
  6. array[i] = i * 5;
  7. const sum = myaddon.ArrayBuffSum(array.buffer);
  8. console.log();
  9. console.log(`js: Sum of the array = ${sum}`);
  10. }
  11. test1();

运行输出:

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/339388
推荐阅读
相关标签
  

闽ICP备14008679号