1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] PythonからC/C++関数呼び出し Pybind11

1
Last updated at Posted at 2025-12-19

はじめに

Pythonは書きやすく開発速度も速い反面、重たい処理を行うと実行速度がネックになります。
場合によっては 処理が終わる前に日が変わる こともあります。

そこで登場するのが pybind11 です。
pybind11を使うことで C/C++で実装した関数をPythonから直接呼び出す ことができ、
計算量の多い処理だけをC/C++に逃がすことで、速度の恩恵を受けられます。

この記事では要点だけをまとめます。


pybind11とは

  • C/C++関数をPythonモジュールとして公開できるライブラリ
  • Python ↔ C++ の橋渡しを最小コードで実現できる
  • 計算部分をC/C++に任せることで大幅な高速化が可能

インストール

pip install pybind11

C/C++サンプルコード

example.cpp
#include <pybind11/pybind11.h>

// 1. 高速化したいC++関数
int add(int i, int j) {
    return i + j;
}

// 2. Pythonモジュールとしての定義
// PYBIND11_MODULE(モジュール名, 変数名)
PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin"; // モジュールのドキュメント文字列
    
    // Python側での関数名, C++側の関数ポインタ, ドキュメント文字列
    m.def("add", &add, "A function that adds two numbers");
}

ビルド用スクリプト

setup.py
from setuptools import setup, Extension
import pybind11

ext_modules = [
    Extension(
        "example",                     # モジュール名
        ["example.cpp"],               # ソースファイル
        include_dirs=[pybind11.get_include()],
        language="c++",
        extra_compile_args=[
            "-O3",                      # 最適化(重要)
            "-std=c++17"                # C++標準指定
        ],
    ),
]

setup(
    name="example",
    version="0.0.0",
    author="User",
    description="A simple example using pybind11",
    ext_modules=ext_modules,
)

ビルド

python setup.py build_ext --inplace

Pythonコード

main.py
import example
import time

# C++関数の呼び出し
result = example.add(3, 5)
print(f"3 + 5 = {result}")

# もし重たい処理を実装した場合は、ここでベンチマークを取ると違いがわかります
start = time.time()
# example.heavy_calculation() # C++で実装した重い処理
print(f"Time: {time.time() - start}")

なぜ速くなるのか

  • Pythonは動的型付けのため、演算ごとに型チェックが発生する
  • C/C++はコンパイル時に型が確定し、最適化されたネイティブコードで実行される

よって、計算部分をC/C++に逃がすだけで劇的に高速化できます。

まとめ

Pythonが遅いなら無理にPythonだけで戦わない。
重たい処理はC/C++で書き、Pythonは司令塔。

「Pythonはクソですね」

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?