|
// A sample of python embedding (calling python classes from within C++ code)
//
// To run:
// 1) setenv PYTHONPATH ${PYTHONPATH}:./
// 2) call_class py_source Multiply multiply
// 3) call_class py_source Multiply multiply 9 8
//
#include <Python.h>
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pClass, *pInstance, *pValue;
int i, arg[8];
if (argc < 4)
{
fprintf(stderr,"Usage: call python_filename class_name function_name\n");
return 1;
}
Py_Initialize();
pName = PyString_FromString(argv[1]);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
// Build the name of a callable class
pClass = PyDict_GetItemString(pDict, argv[2]);
// Create an instance of the class
if (PyCallable_Check(pClass))
{
pInstance = PyObject_CallObject(pClass, NULL);
}
// Build parameter list
if( argc > 4 )
{
for (i = 0; i < argc - 4; i++)
{
arg[i] = atoi(argv[i + 4]);
}
// Call a method of the class with two parameters
pValue = PyObject_CallMethod(pInstance, argv[3], "(ii)", arg[0], arg[1]);
} else
{
// Call a method of the class with no parameters
pValue = PyObject_CallMethod(pInstance, argv[3], NULL);
}
if (pValue != NULL)
{
printf("Return of call : %d\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
}
else
{
PyErr_Print();
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);
Py_Finalize();
return 0;
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Jun is an experienced software architect. He wrote his first computer code on the tape machine for a "super computer". The tape machine reads holes on the black pape tape as source code. When manually fixing code, you need a punch and tranparent tape. To delete code, you block holes or cut off a segment and glue two ends together. To change code, you block old holes and punch new holes. You already know how to add new code, don't you? Anyway, that was his programming story in early 1980's.
Jun completed
university with the specialty in oceanography, and
graduate study in meteorology. He obtained his
Ph.D. in physics. Jun has worked in a number of different areas. Since mid-90's, he has been working as a software professional in both military & commercial industries, including
Visual Defence,
Atlantis Systems International and
Array Systems Computing.
Currently, Jun is an architect at
GuestLogix, the global leader in providing onboard retail solutions for airlines and other travel industries. He is also the founder of
Intribute Dynamics, a consulting firm specialized in software development. He has a personal
blog site, although he is hardly able to keep it up to date.
In his spare time, Jun loves classic music, table tennis, and NBA games. During the summer, he enjoyes camping out to the north and fishing on wild lakes.