hello_procedural.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python3
  3. #
  4. # Copyright (C) 2019 Intel Corporation. All rights reserved.
  5. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. #
  7. import ctypes
  8. import wamr.ffi as ffi
  9. WAMS_BINARY_CONTENT = (
  10. b"\x00asm\x01\x00\x00\x00\x01\x84\x80\x80\x80\x00\x01`\x00\x00\x02\x8a\x80"
  11. b"\x80\x80\x00\x01\x00\x05hello\x00\x00\x03\x82\x80\x80\x80\x00\x01\x00"
  12. b"\x07\x87\x80\x80\x80\x00\x01\x03run\x00\x01\n\x8a\x80\x80\x80\x00\x01"
  13. b"\x84\x80\x80\x80\x00\x00\x10\x00\x0b"
  14. )
  15. @ffi.wasm_func_cb_decl
  16. def hello_callback(args, results):
  17. print("Calling back...")
  18. print("> Hello World!")
  19. def main():
  20. print("Initializing...")
  21. engine = ffi.wasm_engine_new()
  22. store = ffi.wasm_store_new(engine)
  23. print("Loading binary...")
  24. # for convenience, use binary content instead of open file
  25. # with open("./hello.wasm", "rb") as f:
  26. # wasm = f.read()
  27. wasm = WAMS_BINARY_CONTENT
  28. binary = ffi.wasm_byte_vec_t()
  29. ffi.wasm_byte_vec_new_uninitialized(binary, len(wasm))
  30. # underlying buffer is not writable
  31. binary.data = (ctypes.c_ubyte * len(wasm)).from_buffer_copy(wasm)
  32. print("Compiling module...")
  33. module = ffi.wasm_module_new(store, binary)
  34. if not module:
  35. raise RuntimeError("Compiling module failed")
  36. binary.data = None
  37. ffi.wasm_byte_vec_delete(binary)
  38. print("Creating callback...")
  39. hello_type = ffi.wasm_functype_new_0_0()
  40. hello_func = ffi.wasm_func_new(
  41. store,
  42. hello_type,
  43. hello_callback,
  44. )
  45. ffi.wasm_functype_delete(hello_type)
  46. print("Instantiating module...")
  47. imports = ffi.wasm_extern_vec_t()
  48. ffi.wasm_extern_vec_new((imports), 1, ffi.wasm_func_as_extern(hello_func))
  49. instance = ffi.wasm_instance_new(store, module, imports, None)
  50. ffi.wasm_func_delete(hello_func)
  51. print("Extracting export...")
  52. exports = ffi.wasm_extern_vec_t()
  53. ffi.wasm_instance_exports(instance, exports)
  54. run_func = ffi.wasm_extern_as_func(exports.data[0])
  55. if not run_func:
  56. raise RuntimeError("can not extract exported function")
  57. ffi.wasm_instance_delete(instance)
  58. ffi.wasm_module_delete(module)
  59. print("Calling export...")
  60. args = ffi.wasm_val_vec_t()
  61. results = ffi.wasm_val_vec_t()
  62. ffi.wasm_val_vec_new_empty(args)
  63. ffi.wasm_val_vec_new_empty(results)
  64. ffi.wasm_func_call(run_func, args, results)
  65. print("Shutting down...")
  66. ffi.wasm_store_delete(store)
  67. ffi.wasm_engine_delete(engine)
  68. print("Done.")
  69. if __name__ == "__main__":
  70. main()