Skip to content

Latest commit

 

History

History
133 lines (96 loc) · 4.87 KB

README.md

File metadata and controls

133 lines (96 loc) · 4.87 KB

cpp-python-scripting

A C++ application and a Python script calling each other

Let your users script your C++ application with their own Python. One binary, a few files, no binding code.

Run Python scripts inside a C++ application, with the Python installed on the user's machine, and let those scripts call the application back.

  • One binary for any Python 3.12 or later (stable ABI).
  • On Windows, the application starts even when Python is missing.
  • One method to override to publish your functions. No binding code, no JSON to handle.
  • No dependency. Windows (MSVC) and Linux.

Usage

Python calls C++

C++: your application publishes set_compute_limit

#include "pyhost.h"

class MyApplication : public pyhost::Host
{
	pyhost::Value method_called(const std::string& name, const pyhost::Value& params) override
	{
		if (name == "set_compute_limit")
		{
			set_compute_limit(params.get_int("limit"));
			return {};
		}
		return Host::method_called(name, params);		// unknown method
	}
};

MyApplication app;
if (app.initialize() != pyhost::Status::Ok)			// or initialize("C:/path/to/python")
	std::cerr << app.error();
app.run("script.py");

Python: script.py calls it

import app
app.set_compute_limit(limit=30)

C++ calls Python

C++: call a function of the script, with its parameters given by name

const pyhost::Value params = pyhost::Value::object().set("limit", 50).set("reverse", true);
pyhost::Value result;
if (app.call("primes", params, &result))
	for (const pyhost::Value& prime : result.items())
		std::cout << prime.as_int() << '\n';

Python: the function, in the script run by app.run

def primes(limit, reverse=False):
    found = [n for n in range(2, limit + 1) if all(n % d for d in range(2, int(n ** 0.5) + 1))]
    return found[::-1] if reverse else found

Methods of pyhost::Host

Method Role
initialize(folder) Finds and starts Python: Ok, NotFound, TooOld or Failed
check(path) Compiles a script without running it
run(path) Runs a script
call(function, params, &result) Calls a function of the last script run
method_called(name, params) Override: Python calls C++
output(stream, line) Override: receives what Python prints, line by line. By default, writes it to the console with the date
set_date_format(format), now() Date of the default output (strftime codes, "" for none), current date in this format
error(), version() Last error, version of Python

When initialize answers NotFound, ask the user for the folder of Python and call it again.

Build

Windows

You need Visual Studio, CMake 3.26 or later and Python 3.12 or later.

cmake -B build
cmake --build build --config Release
build\Release\example.exe

To use the library, add pyhost.cpp, pyhost.h, pyhost_json.h and pyhost_date.h to your C++17 project, link delayimp.lib and advapi32.lib, and set /DELAYLOAD:python3.dll. logger.h and logger.cpp are an optional logger used by the example.

Linux

For Debian, Ubuntu and their derivatives, with Python 3.12 or later:

sh linux/build.sh
./build-linux/example

The script installs the packages of the build (it asks for the sudo password), compiles, then makes the program independent of the version of Python:

  1. The program is linked to libpython3.X.so, X being the version of the build system.
  2. patchelf asks for libpython3.so instead, searched beside the program.
  3. link-python.sh creates this link towards the newest Python of the system. Run it on each machine where the program is installed (sh link-python.sh folder-of-the-program), for example from the postinst of a package.

On Linux, Python is required to start the program, and the folder given to initialize is ignored. Build on the oldest system the program must work on.

How it works (Windows)

  1. Search. The registry (SOFTWARE\Python\PythonCore), then the PATH.
  2. Loading. python3.dll is loaded from that folder. Thanks to /DELAYLOAD, the executable does not need it to start.
  3. Python calls C++. PyImport_AppendInittab, before the initialization, declares a built-in module with two C functions: one for the calls, one for the output.
  4. The app module. A few lines of Python turn app.anything(a=1) into one native call with a name and a JSON text.

Traps

  • _DEBUG: hide it before #include <Python.h>, otherwise a debug build asks for the debug libraries of Python.
  • Delay loading (Windows): the data of a delay loaded DLL cannot be used. No Py_None, Py_RETURN_NONE or PyExc_RuntimeError.
  • Stable ABI: define Py_LIMITED_API. Some usual functions, such as PyRun_SimpleString, are not available.
  • C++ exceptions must never cross Python.

License

MIT