setup.pyとexample.cppを記載後 python setup.py build_ext --inplaceでコンパイル で作ったc++のファイルをコンパイル
pythonの他ファイルで import example print(example.add(3, 5)) # 8 のように実行
from setuptools import setup, Extension import pybind11
ext_modules = [ Extension( 'example', # Pythonから import するモジュール名 ['example.cpp'], # C++ファイル include_dirs=[pybind11.get_include()], language='c++' ), ]
setup( name='example', ext_modules=ext_modules, )
#include <pybind11/pybind11.h>
namespace py = pybind11;
// C++で作った関数 int add(int i, int j) { return i + j; }
// モジュール定義 PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example plugin"; // モジュールの説明 m.def("add", &add, "A function which adds two numbers"); }
//python setup.py build_ext --inplaceでコンパイル