Skip to content

Instantly share code, notes, and snippets.

@amir-saniyan
Created August 17, 2020 10:04
Show Gist options
  • Save amir-saniyan/088795c32839f3211ae104eaff8a499e to your computer and use it in GitHub Desktop.
Save amir-saniyan/088795c32839f3211ae104eaff8a499e to your computer and use it in GitHub Desktop.
C++ implementation of "Hello World" embedding Python

Embedding Python

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']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment