3_list_operation.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * This example demonstrates how to build a List object and how to access its elements.
  3. * It creates a python module named "math_utils" and bind a function named "average" to it.
  4. * It exercises creating a List and accessing its elements.
  5. * It also demonstrates how to cast a python object to a C++ type.
  6. */
  7. #include "pocketpy.h"
  8. using namespace pkpy;
  9. int main(){
  10. // Create a virtual machine
  11. VM* vm = new VM();
  12. // Create a module
  13. PyObject* math_utils = vm->new_module("math_utils");
  14. // Bind a function named "average" to the module
  15. vm->bind(math_utils, "average(l: List[float]) -> float",
  16. [](VM* vm, ArgsView args){
  17. // Cast the argument to a list
  18. List& l = py_cast<List&>(vm, args[0]);
  19. double sum = 0;
  20. // Calculate the sum of the list by iterating through the list
  21. for(auto& e : l){
  22. sum += py_cast<double>(vm, e);
  23. }
  24. return py_var(vm, sum / l.size());
  25. });
  26. // Create a list of numbers and covert it to a python object
  27. List numbers;
  28. numbers.push_back(py_var(vm, 1.0));
  29. numbers.push_back(py_var(vm, 2.0));
  30. numbers.push_back(py_var(vm, 3.0));
  31. PyObject* list = py_var(vm, std::move(numbers));
  32. // Call the "average" function
  33. PyObject* f_average = math_utils->attr("average");
  34. PyObject* result = vm->call(f_average, list);
  35. std::cout << "Average: " << py_cast<double>(vm, result) << std::endl; // 2
  36. // Dispose the virtual machine
  37. delete vm;
  38. return 0;
  39. }