0% found this document useful (0 votes)
39 views

Call Python Functions From C++ On Ubuntu 12.04

This document provides code samples to call Python functions from C++. It includes a Python script that defines a main function, and a C++ program that initializes Python, imports the Python module, gets the main function, and calls it, passing a string argument. The C++ program is able to successfully call the Python function and see the expected output. It also demonstrates what happens if the function is called without arguments.

Uploaded by

elpasante
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Call Python Functions From C++ On Ubuntu 12.04

This document provides code samples to call Python functions from C++. It includes a Python script that defines a main function, and a C++ program that initializes Python, imports the Python module, gets the main function, and calls it, passing a string argument. The C++ program is able to successfully call the Python function and see the expected output. It also demonstrates what happens if the function is called without arguments.

Uploaded by

elpasante
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like