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.
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++: 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| 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.
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.exeTo 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.
For Debian, Ubuntu and their derivatives, with Python 3.12 or later:
sh linux/build.sh
./build-linux/exampleThe script installs the packages of the build (it asks for the sudo password), compiles, then makes the program independent of the version of Python:
- The program is linked to
libpython3.X.so, X being the version of the build system. patchelfasks forlibpython3.soinstead, searched beside the program.link-python.shcreates 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 thepostinstof 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.
- Search. The registry (
SOFTWARE\Python\PythonCore), then thePATH. - Loading.
python3.dllis loaded from that folder. Thanks to/DELAYLOAD, the executable does not need it to start. - 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. - The
appmodule. A few lines of Python turnapp.anything(a=1)into one native call with a name and a JSON text.
_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_NONEorPyExc_RuntimeError. - Stable ABI: define
Py_LIMITED_API. Some usual functions, such asPyRun_SimpleString, are not available. - C++ exceptions must never cross Python.
MIT