Created
June 28, 2016 19:13
-
-
Save willblatt/1976da26900def6f14107c36d9e6e6ec to your computer and use it in GitHub Desktop.
Example of embedding python into C++ application
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
/* | |
VC++ Directories | |
---------------- | |
Include Directories: C:\Anaconda3\include | |
Library Directories: C:\Anaconda3\libs | |
*/ | |
#include <iostream> | |
#include <string> | |
#include <Python.h> | |
void pyCmd() { | |
PyRun_SimpleString("import scipy as np\nprint(np.__version__)"); | |
} | |
std::string CallPythonPlugIn(const std::string& s) { | |
Py_Initialize(); | |
// Import the module "plugin" (from the file "plugin.py") | |
PyObject* moduleName = PyUnicode_FromString("plugin"); | |
PyObject* pluginModule = PyImport_Import(moduleName); | |
// Retrieve the "transform()" function from the module. | |
PyObject* transformFunc = PyObject_GetAttrString(pluginModule, "transform"); | |
// Build an argument tuple containing the string. | |
PyObject* argsTuple = Py_BuildValue("(s)", s.c_str()); | |
// Invoke the function, passing the argument tuple. | |
PyObject* result = PyObject_CallObject(transformFunc, argsTuple); | |
// Convert the result to a std::string. | |
//std::string resultStr(PyString_AsString(result)); | |
char *my_result = 0; | |
PyObject * temp_bytes = PyUnicode_AsEncodedString(result, "ASCII", "strict"); // Owned reference | |
if (temp_bytes != NULL) { | |
my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer | |
} else { | |
// TODO: Handle encoding error. | |
} | |
Py_DECREF(temp_bytes); | |
// Free all temporary Python objects. | |
Py_DECREF(moduleName); | |
Py_DECREF(pluginModule); | |
Py_DECREF(transformFunc); | |
Py_DECREF(argsTuple); | |
Py_DECREF(result); | |
Py_Finalize(); | |
return my_result; | |
} | |
int main(int argc, char** argv) { | |
std::string input; | |
std::cout << "Enter string to transform: "; | |
std::getline(std::cin, input); | |
std::string transformed = CallPythonPlugIn(input); | |
std::cout << "The transformed string is: " << transformed.c_str() << | |
std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment