native_impl.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_platform.h"
  6. #include "wasm_export.h"
  7. #include "math.h"
  8. extern bool
  9. wasm_runtime_call_indirect(wasm_exec_env_t exec_env,
  10. uint32_t element_indices,
  11. uint32_t argc, uint32_t argv[]);
  12. // The first parameter is not exec_env because it is invoked by native funtions
  13. void reverse(char * str, int len)
  14. {
  15. int i = 0, j = len - 1, temp;
  16. while (i < j) {
  17. temp = str[i];
  18. str[i] = str[j];
  19. str[j] = temp;
  20. i++;
  21. j--;
  22. }
  23. }
  24. // The first parameter exec_env must be defined using type wasm_exec_env_t
  25. // which is the calling convention for exporting native API by WAMR.
  26. //
  27. // Converts a given integer x to string str[].
  28. // digit is the number of digits required in the output.
  29. // If digit is more than the number of digits in x,
  30. // then 0s are added at the beginning.
  31. int intToStr(wasm_exec_env_t exec_env, int x, char* str, int str_len, int digit)
  32. {
  33. int i = 0;
  34. printf ("calling into native function: %s\n", __FUNCTION__);
  35. while (x) {
  36. // native is responsible for checking the str_len overflow
  37. if (i >= str_len) {
  38. return -1;
  39. }
  40. str[i++] = (x % 10) + '0';
  41. x = x / 10;
  42. }
  43. // If number of digits required is more, then
  44. // add 0s at the beginning
  45. while (i < digit) {
  46. if (i >= str_len) {
  47. return -1;
  48. }
  49. str[i++] = '0';
  50. }
  51. reverse(str, i);
  52. if (i >= str_len)
  53. return -1;
  54. str[i] = '\0';
  55. return i;
  56. }
  57. int get_pow(wasm_exec_env_t exec_env, int x, int y) {
  58. printf ("calling into native function: %s\n", __FUNCTION__);
  59. return (int)pow(x, y);
  60. }
  61. int32_t
  62. calculate_native(wasm_exec_env_t exec_env, int32_t n, int32_t func1,
  63. int32_t func2)
  64. {
  65. printf("calling into native function: %s, n=%d, func1=%d, func2=%d\n",
  66. __FUNCTION__, n, func1, func2);
  67. uint32_t argv[] = { n };
  68. if (!wasm_runtime_call_indirect(exec_env, func1, 1, argv)) {
  69. printf("call func1 failed\n");
  70. return 0xDEAD;
  71. }
  72. uint32_t n1 = argv[0];
  73. printf("call func1 and return n1=%d\n", n1);
  74. if (!wasm_runtime_call_indirect(exec_env, func2, 1, argv)) {
  75. printf("call func2 failed\n");
  76. return 0xDEAD;
  77. }
  78. uint32_t n2 = argv[0];
  79. printf("call func2 and return n2=%d\n", n2);
  80. return n1 + n2;
  81. }