Skip to content

Instantly share code, notes, and snippets.

@andrei-pokrovsky
Forked from willblatt/embed_python.cc
Created July 11, 2022 07:20
Show Gist options
  • Save andrei-pokrovsky/ae355ea244762d677be45eaff7ed28c1 to your computer and use it in GitHub Desktop.
Save andrei-pokrovsky/ae355ea244762d677be45eaff7ed28c1 to your computer and use it in GitHub Desktop.
Example of embedding python into C++ application
/*
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