2_module_and_binding.cpp 935 B

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * This example demonstrate the process of creating a python module and
  3. * bind a function to it, as well as the procedure for calling the function.
  4. */
  5. #include "pocketpy.h"
  6. using namespace pkpy;
  7. int main(){
  8. // Create a virtual machine
  9. VM* vm = new VM();
  10. // Create a module
  11. PyObject* math_module = vm->new_module("math");
  12. // Bind a function named "add" to the module
  13. vm->bind(math_module, "add(a: int, b: int) -> int",
  14. [](VM* vm, ArgsView args){
  15. int a = py_cast<int>(vm, args[0]);
  16. int b = py_cast<int>(vm, args[1]);
  17. return py_var(vm, a + b);
  18. });
  19. // Call the "add" function
  20. PyObject* f_sum = math_module->attr("add");
  21. PyObject* result = vm->call(f_sum, py_var(vm, 4), py_var(vm, 5));
  22. std::cout << "Sum: " << py_cast<int>(vm, result) << std::endl; // 9
  23. // Dispose the virtual machine
  24. delete vm;
  25. return 0;
  26. }