1_type_cast.cpp 906 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * This example demonstrates the type casting feature of PocketPy.
  3. * It creates a virtual machine and cast PyObject* to different types.
  4. */
  5. #include "pocketpy.h"
  6. using namespace pkpy;
  7. int main(){
  8. // Create a virtual machine
  9. VM* vm = new VM();
  10. PyObject* str_obj = py_var(vm, "hello world");
  11. // Cast PyObject* to Str type
  12. Str& str = py_cast<Str&>(vm, str_obj);
  13. std::cout << "string: " << str.c_str() << std::endl; // hello world
  14. PyObject* int_obj = py_var(vm, 10);
  15. // Cast PyObject* to Int type
  16. int int_var = py_cast<int>(vm, int_obj);
  17. std::cout << "int: " << int_var << std::endl; // 10
  18. PyObject* float_obj = py_var(vm, 10.5);
  19. // Cast PyObject* to double type
  20. double float_var = py_cast<double>(vm, float_obj);
  21. std::cout << "float: " << float_var << std::endl; // 10.5
  22. // Dispose the virtual machine
  23. delete vm;
  24. return 0;
  25. }