文章目錄
- 前言
- 1.將pybind11 clone至當前項目下的extern目錄下
- 2.在CmakeLists.txt中將pybind11項目包含
- 3.接口cpp文件格式
- 4.編譯
- 5.導入Python使用
- 6.性能比較
- pybind11項目地址
前言
通過https://github.com/pybind/pybind11項目實現Python調用C/C++代碼
實現步驟
1.將pybind11 clone至當前項目下的extern目錄下
git clone https://github.com/pybind/pybind11.git
2.在CmakeLists.txt中將pybind11項目包含
cmake_minimum_required(VERSION 3.10)project(python_call_c)# set(PYTHON_EXECUTABLE "/usr/bin/python3")
# set(PYTHON_INCLUDE_DIRECTORY "/usr/include/python3.10")add_subdirectory(extern/pybind11)pybind11_add_module(UserPythonModule test.cpp)
其中pybind11_add_module是由pybind11庫提供的cmake宏,必須將pybind11項目包含后才會包含該宏。
UserPythonModule為Python導入模塊的名字,test.cpp: 這是包含要綁定到 Python 的 C++ 代碼的源文件
3.接口cpp文件格式
#include "extern/pybind11/include/pybind11/pybind11.h"int add(int a, int b)
{return a + b;
}PYBIND11_MODULE(UserPythonModule/* python module name */, m/*variable*/)
{m.doc() = "jslkdjf"; // optional module docstring// 定義模塊內的函數m.def("add"/*module function name*/, &add/*bind with c func*/, "Afun"/*fun docstring*/);
}
第一行為導入的pybind11的頭文件
- PYBIND11_MODULE:頭文件宏
- m:參數,代表這個模塊
- m.doc(): 模塊的docstring
- m.def: 在模塊內定義一個函數
- “add”:函數名
- &add:綁定到C的函數指針
- function的docstring
4.編譯
編譯項目,在編譯時可能會包找不到頭文件<Python.h>,意味著編譯器無法找到Python開發庫的頭文件。需要安裝Python開發庫
apt-get install python3-dev
編譯:
mkdir build
cd build
cmake ..
make
編譯好后會有一個名為UserPythonModule.cpython-310-x86_64-linux-gnu.so
的庫文件
5.導入Python使用
import UserPythonModule
UserPythonModule.add(4, 6)
6.性能比較
import UserPythonModuleimport time# 記錄開始時間
start_time = time.time()# 執行你的代碼段
# 例如:
sum = 0
for i in range(10000000):sum += i# 記錄結束時間
end_time = time.time()# 計算執行時間
execution_time = end_time - start_timeprint("python 執行結果為:", sum, " 代碼執行時間為:", execution_time, "秒")
print("-----------------")start_time = time.time()
sum = UserPythonModule.add(10000000-1)
end_time = time.time()
execution_time = end_time - start_time
print("call C 執行結果為:", sum, " 代碼執行時間為:", execution_time, "秒")
out:
python 執行結果為: 49999995000000 代碼執行時間為: 0.4630615711212158 秒
-----------------
call C 執行結果為: 49999995000000 代碼執行時間為: 0.006102561950683594 秒
pybind11項目地址
https://github.com/pybind/pybind11