hello-embed.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 Paul Sokolovsky
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <string.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include "py/compile.h"
  30. #include "py/runtime.h"
  31. #include "py/gc.h"
  32. #include "py/stackctrl.h"
  33. static char heap[16384];
  34. mp_obj_t execute_from_str(const char *str) {
  35. nlr_buf_t nlr;
  36. if (nlr_push(&nlr) == 0) {
  37. mp_lexer_t *lex = mp_lexer_new_from_str_len(0/*MP_QSTR_*/, str, strlen(str), false);
  38. mp_parse_tree_t pt = mp_parse(lex, MP_PARSE_FILE_INPUT);
  39. mp_obj_t module_fun = mp_compile(&pt, lex->source_name, MP_EMIT_OPT_NONE, false);
  40. mp_call_function_0(module_fun);
  41. nlr_pop();
  42. return 0;
  43. } else {
  44. // uncaught exception
  45. return (mp_obj_t)nlr.ret_val;
  46. }
  47. }
  48. int main() {
  49. // Initialized stack limit
  50. mp_stack_set_limit(40000 * (BYTES_PER_WORD / 4));
  51. // Initialize heap
  52. gc_init(heap, heap + sizeof(heap));
  53. // Initialize interpreter
  54. mp_init();
  55. const char str[] = "print('Hello world of easy embedding!')";
  56. if (execute_from_str(str)) {
  57. printf("Error\n");
  58. }
  59. }
  60. uint mp_import_stat(const char *path) {
  61. return MP_IMPORT_STAT_NO_EXIST;
  62. }
  63. void nlr_jump_fail(void *val) {
  64. printf("FATAL: uncaught NLR %p\n", val);
  65. exit(1);
  66. }