Skip to content

AI STUDIO Taiwan

台 灣 人 工 智 慧 與 資 料 科 學 研 究 室

  • About 關於本站
  • 專欄列表
  • Taiwan NLP.台灣自然語言處理與人工智慧交流社( 1.8萬位成員)
  • 關於 Taiwan NLP 社群

【C++ 應用】使用pybind11製作讓Python呼叫C++函式庫的介面

Posted on 2022 年 8 月 7 日2023 年 8 月 10 日 By 楊 明翰 在〈【C++ 應用】使用pybind11製作讓Python呼叫C++函式庫的介面〉中尚無留言
C++ 應用
Print Friendly, PDF & Email

pybind11可以自動幫我們搞定C++和Python型別的串接,讓我們不需要直接處理底層的型別,這對於需要使用C++做部份加速的專案來說,可以讓開發者專住在C++內的開發上。這裡簡單介紹如何使用基本的pybind11的方式。這裡的範例是從官方的https://pybind11.readthedocs.io/en/stable/basics.html 當中改寫以及實驗的結果。

內容目錄

  • 安裝pybind11
  • C++ Part
  • CMake Part
  • Python Part

安裝pybind11

pip install pybind11

C++ Part

C++部份這裡展示四個函式,以及使用pybind11提供的micro,最主要的PYBIND11_MODULE,來註冊要提供給Python的函式,須引入<pybind11/pybind11.h>。另外由於要讓pybind11能自動處理C++的STL的型別,這裡還需要引入<pybind11/stl.h>。

C++
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>


#include <iostream>
#include <numeric>
#include <vector>


int add(int a, int b) { return a + b; }


int sub(int a, int b) { return a - b; }


int sum(std::vector<int> &arr) {
 int sum = 0;
 return accumulate(arr.begin(), arr.end(), sum);
}
void hello_world(void) {
 std::cout << "Hello World!" << std::endl;
 return;
}
PYBIND11_MODULE(sum_and_hello, m) {
 m.def("add", &add, "add two value function");
 m.def("sub", &sub, "sub two value function", pybind11::arg("a"), pybind11::arg("b"));
 m.def("sum", &sum, "sum up function");
 m.def("hello_world", &hello_world, "hello world function");
}

C++的部份註冊函式的寫法為

PYBIND11_MODULEE(模組名稱, m) 

以及

m.def("函式名稱", 函式位址(也就是&函式), "函式介紹");

如果有需要指定參數名稱,可以用

pybind11::arg

CMake Part

編譯C++函式庫的部份使用cmake,主要是用pybind11_add_module: (CMakeLists.txt)

CMake
cmake_minimum_required(VERSION 3.18)
set(NAME sum_and_hello)
project(${NAME})
set(CMAKE_CXX_FLAGS "-std=c++11" )
set(CMAKE_BUILD_TYPE "Release")
find_package(PythonLibs 3.9.5 REQUIRED)
find_package(PythonInterp 3.9.5 REQUIRED)
set(pybind11_DIR /media/whuang022/DATA/anaconda3/lib/python3.7/site-packages/pybind11/share/cmake/pybind11)
find_package(pybind11 REQUIRED CONFIG )
pybind11_add_module(module ${NAME}.cpp)
set_target_properties(module PROPERTIES OUTPUT_NAME ${NAME})
set_target_properties(module PROPERTIES SUFFIX ".so")

這裡記得手動引入pybind11_DIR的位置(由於我這邊環境的關係,pybind11裝在python3.7內)

這樣編譯C++的部份,就可以在終端機跑camke和make

mkdir build
cd build
cmake ..
make

完成編譯後得到會得到sum_and_hello.so,並複製到Python專案內即可。

Python Part

這裡模組名稱為sum_and_hello,可以像一般引入模組一樣使用它(run.py):

Python
import sum_and_hello




sum_and_hello.hello_world()


x = sum_and_hello.add(1, 2)
print(x)
y = sum_and_hello.sub(b=1, a=2)
print(y)
z = sum_and_hello.sum([1, 2, 3])
print(x)

這時候在終端機執行

 python run.py

可以得到

Hello World!
3
1
3

以上便是用pybind11讓Python呼叫C++的使用方式的簡單介紹。

✔ 幫我們按個喜歡和分享,支持我們

平均分數 5 / 5. 給分人數 1

尚未有評分,請幫我評分歐

楊 明翰
楊 明翰

是一名八年級中段班的創業者與資料科學家

“With belief and action, we change the world.”

憑藉信念與行動,我們改變世界💪

更多關於站長

本文允許重製、散布、傳輸以及修改,但不得為商業目的之使用

使用時必須註明出處自:楊明翰 , 台灣人工智慧與資料科學研究室 https://aistudio.tw

標籤: pybind11 現代C++

文章導覽

❮ Previous Post: 【C++ 應用】Xtensor 一維陣列的使用
Next Post: 【站長哲學】關於近未來,AGI通用人工智慧對學習和知識的想象 ❯

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

更多AI相關資訊,歡迎加入站長的粉絲團

Facebook

閱讀視覺風格選擇


實驗袍白 / 適合資料分析師、科學家
終端機黑 / 適合黑客、電腦工程師

專欄列表

  • Artificial intelligence 人工智慧 (3)
    • HPC 高效能運算 (1)
    • PyTorch (1)
    • 從頭實作AI (1)
  • Backend 後端開發 (1)
  • C++ 應用 (2)
  • Community 社群介紹 (1)
  • Data Engineering 資料工程與訊號分析 (1)
  • Java 開發與教學 (2)
  • Linux 入門 (5)
  • NLP/NLU 自然語言處理與理解 (4)
  • Philosophy 站長哲學 (5)
  • Python 開發與教學 (7)
    • Python Flask 網站開發 (1)
    • Python 中階 (1)
    • Python 入門 (5)
  • Slides會議簡報 (12)
  • Start-up 創新創業 (7)
  • 機器學習數學基礎 (1)
  • 私人筆記手稿 (4)
  • 線上教學目錄 (4)

近期發布

  • 【Linux 應用】使用Zenity零成本開發的多開瀏覽器管理器
  • 【Start-up 創新創業】如何選擇創業題目
  • 【自然語言處理與理解】Llama-2大語言模型CPU版本使用
  • 【個人演講】AI EXPO 2023 ChatGPT以及LLM
  • 【自訓課程】NGS 次世代基因體資料科學 課程

討論

尚無留言可供顯示。

年份彙整

  • 2023 (9)
  • 2022 (4)
  • 2021 (6)
  • 2020 (14)
  • 2019 (8)
  • 2018 (10)
  • 2017 (2)
  • 2016 (4)
  • 2015 (2)

ChatGPT GRU HPC llama-cpp LLM Log4J LSTM Node.js SMO SVM Zenity 人工智慧 人格特質 出資 創新 創業 多語言 多開瀏覽器 大語言模型 感知機 戰鬥 技術 技術合夥 技術股 撰寫程式 新創 新手 新聞輿情 最佳化 機器學習 死亡 現代C++ 系統日誌 股東權益 能力 證明 變數 負債 資本 資產負債表 長短期記憶 霍普菲爾 類神經網 類神經網路 風險

調整字型大小

A 縮小字型大小。 A 重設字型大小。 A 放大字型大小。

Copyright © 2023 AI STUDIO Taiwan.
聯絡我們 : whuang022@gmail.com
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Theme: Oceanly by ScriptsTown