Skip to content

Instantly share code, notes, and snippets.

@auxiliary
Created April 13, 2017 01:34
Show Gist options
  • Save auxiliary/d74a0db50eb2bff95f9f01db1cbdec0c to your computer and use it in GitHub Desktop.
Save auxiliary/d74a0db50eb2bff95f9f01db1cbdec0c to your computer and use it in GitHub Desktop.
Sample code to call a python function in cpp
#include <python2.7/Python.h>
#include <iostream>
int main(int argc, char *argv[])
{
PyObject *pModule, *pModuleName, *pDict, *pFunc, *pValue, *pArgs;
Py_Initialize();
pModuleName = PyString_FromString("pie");
pModule = PyImport_Import(pModuleName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "foo");
if (PyCallable_Check(pFunc))
{
pArgs = PyTuple_New(2);
pValue = PyString_FromString("foo");
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyString_FromString("bar");
PyTuple_SetItem(pArgs, 1, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
}
else
{
PyErr_Print();
}
PyErr_Print();
printf("%s\n", PyString_AsString(pValue));
Py_DECREF(pModule);
Py_DECREF(pModuleName);
Py_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment