main.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (C) 2019 Intel Corporation. All rights reserved.
  2. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  3. from wamr.wamrapi.wamr import Engine, Module, Instance, ExecEnv
  4. from ctypes import c_uint
  5. import pathlib
  6. from ctypes import c_int32
  7. from ctypes import c_uint
  8. from ctypes import c_void_p
  9. from ctypes import cast
  10. from ctypes import CFUNCTYPE
  11. from wamr.wamrapi.iwasm import NativeSymbol
  12. from wamr.wamrapi.iwasm import String
  13. from wamr.wamrapi.wamr import ExecEnv
  14. def python_func(env: int, value: int) -> int:
  15. print("python: in python_func with input:", value)
  16. # Example of generating ExecEnv from `wasm_exec_env_t``
  17. exec_env = ExecEnv.wrap(env)
  18. add = exec_env.get_module_inst().lookup_function("add")
  19. const = 1000
  20. argv = (c_uint * 2)(value, const)
  21. print(f"python: calling add({value}, {const})")
  22. exec_env.call(add, 2, argv)
  23. res = argv[0]
  24. print("python: result from add:", res)
  25. return res + 1
  26. native_symbols = (NativeSymbol * 1)(
  27. *[
  28. NativeSymbol(
  29. symbol=String.from_param("python_func"),
  30. func_ptr=cast(
  31. CFUNCTYPE(c_int32, c_void_p, c_int32)(python_func), c_void_p
  32. ),
  33. signature=String.from_param("(i)i"),
  34. )
  35. ]
  36. )
  37. def main():
  38. engine = Engine()
  39. engine.register_natives("env", native_symbols)
  40. module = Module.from_file(engine, pathlib.Path(__file__).parent / "func.wasm")
  41. module_inst = Instance(module)
  42. exec_env = ExecEnv(module_inst)
  43. func = module_inst.lookup_function("c_func")
  44. inp = 10
  45. print(f"python: calling c_func({inp})")
  46. argv = (c_uint)(inp)
  47. exec_env.call(func, 1, argv)
  48. print("python: result from c_func:", argv.value)
  49. if __name__ == "__main__":
  50. main()