native_impl.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // The first parameter is not exec_env because it is invoked by native functions
  9. void
  10. reverse(char *str, int len)
  11. {
  12. int i = 0, j = len - 1, temp;
  13. while (i < j) {
  14. temp = str[i];
  15. str[i] = str[j];
  16. str[j] = temp;
  17. i++;
  18. j--;
  19. }
  20. }
  21. // The first parameter exec_env must be defined using type wasm_exec_env_t
  22. // which is the calling convention for exporting native API by WAMR.
  23. //
  24. // Converts a given integer x to string str[].
  25. // digit is the number of digits required in the output.
  26. // If digit is more than the number of digits in x,
  27. // then 0s are added at the beginning.
  28. int
  29. intToStr(wasm_exec_env_t exec_env, int x, char *str, int str_len, int digit)
  30. {
  31. int i = 0;
  32. printf("calling into native function: %s\n", __FUNCTION__);
  33. while (x) {
  34. // native is responsible for checking the str_len overflow
  35. if (i >= str_len) {
  36. return -1;
  37. }
  38. str[i++] = (x % 10) + '0';
  39. x = x / 10;
  40. }
  41. // If number of digits required is more, then
  42. // add 0s at the beginning
  43. while (i < digit) {
  44. if (i >= str_len) {
  45. return -1;
  46. }
  47. str[i++] = '0';
  48. }
  49. reverse(str, i);
  50. if (i >= str_len)
  51. return -1;
  52. str[i] = '\0';
  53. return i;
  54. }
  55. int
  56. get_pow(wasm_exec_env_t exec_env, int x, int y)
  57. {
  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. }