封裝Python和調用C++模塊的坑(使用pyinstaller和pybind11)


Python 部分

依賴庫的 pip 安裝

創建虛擬環境並進入虛擬環境:

conda create --name bundle python=3.7
conda activate bundle

在虛擬環境下:

pip install torch===1.3.1 torchvision==0.2.2.post3 -f https://download.pytorch.org/whl/torch_stable.html
pip install opencv-python==4.2.0.32 dlib==19.19.0 pyinstaller==3.6

Pillow 的版本不能過高,需要降級:

pip install --upgrade pillow==6.0.0

setuptools 的版本不能過高,需要降級:

pip install --upgrade setuptools==40.8.0


C++ 部分

pybind11

頭文件

  • 在 include 中包含 pybind11 頭文件。
  • 把 Python 虛擬環境頭文件路徑裝進來:D:\develop\Anaconda3\envs\bundle\include。

庫文件

把 Python 虛擬環境(注意,一定要是 pyinstaller 所在的那個虛擬環境)的庫文件目錄裝進來:D:\develop\Anaconda3\envs\bundle\libs。

加入鏈接庫文件:

_tkinter.lib
python3.lib
python37.lib

暴露接口

 1 #include <pybind11/pybind11.h>
 2 namespace py = pybind11;
 3 
 4 #include <iostream>
 5 #include "SingleKinect.h"
 6 
 7 
 8 PYBIND11_MODULE(main, m) {
 9 // shorthand
10 using namespace pybind11::literals;
11 m.doc() = "pybind11 example plugin";
12 
13 // Creating bindings for a custom type
14 py::class_<ws_tech::SingleKinect>(m, "SingleKinect")
15 .def(py::init<py::function, int>())
16 .def("Open", &ws_tech::SingleKinect::Open)
17 .def("Running", &ws_tech::SingleKinect::Running)
18 .def("Close", &ws_tech::SingleKinect::Close);
19 }

更改輸出類型:動態庫、后綴為 pyc。

打包過程問題

pyinstall 打包

pyinstaller -F .\runner.py

必要的運行時庫

  • vcruntime140_1.dll

 

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM