LoginSignup
6
5

More than 3 years have passed since last update.

pybind11 +cmake で Python interpreter を C++ アプリに embed する

Last updated at Posted at 2020-10-14

いつの頃からか, pybind11 でお手軽に python interpreter を埋め込んで exe ビルドできるようになっていました.

C++ がメインだったり, エントリポイントが C/C++ のプログラムの場合に役立ちます.

デフォルトでは, システムを探索して見つかった libPython とリンクします(conda などの場合は conda 環境の python など)

Python を明示的に指定したい場合は

cmake -DPYTHON_EXECUTABLE=/path/to/bin/python ... と, PYTHON_EXECUTABLE でしていします.
(lib も bin ディレクトリをベースに見つけてくれるっぽい)

pybind11 が内部的には find_package(PythonInterp) しているためです.

ちなみに python3.8m など suffix がついていたりしますが, suffix の意味はこちら.

実行時エラーの対処

Python を Embed した C++ アプリをそのまま実行すると, site module が見つからないや,

Fatal Python error: initfsencoding: unable to load the file system codec                                                                    ModuleNotFoundError: No module named 'encodings'  

などのエラーがでるときがあります(特に Windows?).

リンクされている Python 自体は, 自身の Python 環境を知らないためです.

PYTHONHOME 環境変数を適切に設定してあげましょう.
(cmake bootstrap 時に見つかった Python のパスを使うのが理想)

TODO

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5