2013-01-12
Call Python functions from C++ on Ubuntu
12.04
Linux Programming
Codes
/home/shinya/py_example/mymain.py
import sys
def main(args):
sys.stdout.write('Hello, world!\n');
if args:
sys.stdout.write('{0}\n'.format(args))
/home/shinya/py_example/main.cc
#include <Python.h>
#include <cassert>
#include <iostream>
int main(int argc, char** argv) {
Py_Initialize();
assert(Py_IsInitialized());
const char* kModuleName = "mymain";
PyObject* module_name = PyString_FromString(kModuleName);
PyObject* module = PyImport_Import(module_name);
PyObject* dic = PyModule_GetDict(module);
const char* kFuncName = "main";
PyObject* main_func = PyDict_GetItemString(dic, kFuncName);
assert(PyCallable_Check(main_func));
PyObject* main_args = PyTuple_New(1);
PyObject* main_args_0 = PyString_FromString("Hello, Python!");
PyTuple_SetItem(main_args, 0, main_args_0);
PyObject_CallObject(main_func, main_args);
// raise Exception
PyObject_CallObject(main_func, NULL);
PyErr_Print();
Py_Finalize();
return 0;
}
Check
$ export PYTHONPATH=${PYTHONPATH}:/home/shinya/py_example
$ g++ -Wall -I/usr/include/python2.7 main.cc -lpython2.7
$ ./a.out
Hello, world!
Hello, Python!
TypeError: main() takes exactly 1 argument (0 given)
References
Python/C API Reference Manual Python v2.7 documentation