GitHub - rebisway/cpp-python-scripting: Let your users script your C++ application with their own Python 3.12+. Two-way calls, no binding code, Windows and Linux.
Repository navigation
cpp-python-scriptingPublic
About
Let your users script your C++ application with their own Python 3.12+. Two-way calls, no binding code, Windows and Linux.
www.rebisway.comTopics
cpp cpp17 cpython cross-platform embedded-python embeddings plugin-system python scripting stable-abiResources
Readme MIT license ActivityStars
1 starWatchers
0 watchingForks
0 forks Report repositoryBranches
Tags
Go to Branches page Go to Tags page
Latest commit
History
3 Commits
View commit history for this file.
Folders and files
| Name | Name | Last commit message | Last commit date |
|---|---|---|---|
| docs | docs | ||
| linux | linux | ||
| scripts | scripts | ||
| src | src | ||
| .gitattributes | .gitattributes | ||
| .gitignore | .gitignore | ||
| CMakeLists.txt | CMakeLists.txt | ||
| LICENSE | LICENSE | ||
| README.md | README.md | ||
Repository files navigation
cpp-python-scripting
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:
- 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.
How it works (Windows)
- 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.
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_NONEorPyExc_RuntimeError. - Stable ABI : define
Py_LIMITED_API. Some usual functions, such asPyRun_SimpleString, are not available. - C++ exceptions must never cross Python.
License
MIT
About
Let your users script your C++ application with their own Python 3.12+. Two-way calls, no binding code, Windows and Linux.
www.rebisway.com