This gist contains C++ implementation of Hello World
embedding Python.
HelloWorld.cpp:
#include <cstdlib>
#include <stdexcept>
#include <Python.h>
int main(int argc, char* argv[])
{
wchar_t** wargv = new wchar_t*[argc];
for(int i = 0; i < argc; i++)
{
wargv[i] = Py_DecodeLocale(argv[i], nullptr);
if(wargv[i] == nullptr)
{
return EXIT_FAILURE;
}
}
Py_SetProgramName(wargv[0]);
Py_Initialize();
PySys_SetArgv(argc, wargv);
PyRun_SimpleString("import sys");
PyRun_SimpleString("print('Hello World!', sys.argv)");
Py_Finalize();
for(int i = 0; i < argc; i++)
{
PyMem_RawFree(wargv[i]);
wargv[i] = nullptr;
}
delete[] wargv;
wargv = nullptr;
return 0;
}
Install Prerequisites for Compilation*:
$ sudo apt install build-essential pkg-config python3 python3-dev
Compiling the Source Code:
$ g++ HelloWorld.cpp `pkg-config python3-embed --libs --cflags` -o HelloWorld
Run:
$ ./HelloWorld
$ # Hello World! ['./HelloWorld']
$
$ ./HelloWorld hi
$ # Hello World! ['./HelloWorld', 'hi']