example.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "pocketpy.h"
  2. #include <stdio.h>
  3. static bool int_add(int argc, py_Ref argv) {
  4. PY_CHECK_ARGC(2);
  5. PY_CHECK_ARG_TYPE(0, tp_int);
  6. PY_CHECK_ARG_TYPE(1, tp_int);
  7. py_i64 a = py_toint(py_arg(0));
  8. py_i64 b = py_toint(py_arg(1));
  9. py_newint(py_retval(), a + b);
  10. return true;
  11. }
  12. int main() {
  13. // Initialize pocketpy
  14. py_initialize();
  15. // Hello world!
  16. bool ok = py_exec("print('Hello world!')", "<string>", EXEC_MODE, NULL);
  17. if(!ok) goto __ERROR;
  18. // Create a list: [1, 2, 3]
  19. py_Ref r0 = py_getreg(0);
  20. py_newlistn(r0, 3);
  21. py_newint(py_list_getitem(r0, 0), 1);
  22. py_newint(py_list_getitem(r0, 1), 2);
  23. py_newint(py_list_getitem(r0, 2), 3);
  24. // Eval the sum of the list
  25. py_Ref f_sum = py_getbuiltin(py_name("sum"));
  26. py_push(f_sum);
  27. py_pushnil();
  28. py_push(r0);
  29. ok = py_vectorcall(1, 0);
  30. if(!ok) goto __ERROR;
  31. printf("Sum of the list: %d\n", (int)py_toint(py_retval())); // 6
  32. // Bind native `int_add` as a global variable
  33. py_newnativefunc(r0, int_add);
  34. py_setglobal(py_name("add"), r0);
  35. // Call `add` in python
  36. ok = py_exec("add(3, 7)", "<string>", EVAL_MODE, NULL);
  37. if(!ok) goto __ERROR;
  38. py_i64 res = py_toint(py_retval());
  39. printf("Sum of 2 variables: %d\n", (int)res); // 10
  40. py_finalize();
  41. return 0;
  42. __ERROR:
  43. py_printexc();
  44. py_finalize();
  45. return 1;
  46. }