Guest User

Untitled

a guest
May 21st, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include <iostream>
  2. #include <Python.h>
  3.  
  4. // C++ call Python module
  5. bool CppCallPython()
  6. {
  7. // Python initialize
  8. Py_Initialize();
  9. if (!Py_IsInitialized())
  10. {
  11. std::cout << "Python initialization failed!\n";
  12. return false;
  13. }
  14.  
  15. // If my MyPython.py file is in "/Users/xx/code", set the working path to "/Users/xx/code"
  16. std::string path = "/Users/xx/code";
  17. PySys_SetPath(&path[0u]);
  18.  
  19. // Import MyPython.py module
  20. PyObject* pModule = PyImport_ImportModule("MyPython");
  21. if (!pModule)
  22. {
  23. std::cout <<"Cannot open Python file!\n";
  24. return false;
  25. }
  26.  
  27. // Get the HelloPython() function in the module
  28. PyObject* pFunhello = PyObject_GetAttrString(pModule, "HelloPython");
  29. if (!pFunhello)
  30. {
  31. std::cout << "Failed to get this function!";
  32. return false;
  33. }
  34.  
  35. // Call HelloPython()
  36. PyObject_CallFunction(pFunhello, NULL);
  37.  
  38. // Finalize
  39. Py_Finalize();
  40.  
  41. return true;
  42. }
Add Comment
Please, Sign In to add comment