Created
May 16, 2018 10:18
-
-
Save huihut/b4597d097123a8c8388c71b3f0ff21e5 to your computer and use it in GitHub Desktop.
C++ call Python module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <Python.h> | |
// C++ call Python module | |
bool CppCallPython() | |
{ | |
// Python initialize | |
Py_Initialize(); | |
if (!Py_IsInitialized()) | |
{ | |
std::cout << "Python initialization failed!\n"; | |
return false; | |
} | |
// If my MyPython.py file is in "/Users/xx/code", set the working path to "/Users/xx/code" | |
std::string path = "/Users/xx/code"; | |
PySys_SetPath(&path[0u]); | |
// Import MyPython.py module | |
PyObject* pModule = PyImport_ImportModule("MyPython"); | |
if (!pModule) | |
{ | |
std::cout <<"Cannot open Python file!\n"; | |
return false; | |
} | |
// Get the HelloPython() function in the module | |
PyObject* pFunhello = PyObject_GetAttrString(pModule, "HelloPython"); | |
if (!pFunhello) | |
{ | |
std::cout << "Failed to get this function!"; | |
return false; | |
} | |
// Call HelloPython() | |
PyObject_CallFunction(pFunhello, NULL); | |
// Finalize | |
Py_Finalize(); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you also provide your python code for the complete package ? That might be super helpful