cmake+pybind11打包c++库成python wheel安装包

写在前面

1、本文内容
有时候我们需要用c++代码,供python调用,本文提供将c++库封装成python接口的方法,并将库打包成可通过pip安装的wheel安装包

2、平台/环境
通过cmake构建项目,跨平台通用;pybind11
3、转载请注明出处:
https://blog.csdn.net/qq_41102371/article/details/132046046

准备

1、pybind11

编译安装pybind11

获取源码

mkdir pybind
cd pybind
git clone https://github.com/pybind/pybind11.git

编译安装

cmake -DCMAKE_INSTALL_PREFIX=D:/carlos/install/pybind11 -S ./pybind11 -B ./build
cmake --build ./build --config Release --target install

2、conda

安装conda环境

demo

官方源码

mkdir pybind_test
cd pybind_test
git clone https://github.com/pybind/cmake_example.git
cd cmake_example

修改CMakeLists.txt

注释掉add_subdirectory,通过find package的方式找到上面安装的pybind11

cmake_minimum_required(VERSION 3.4...3.18)
project(cmake_example)

# add_subdirectory(pybind11)
set(pybind11_DIR D:/carlos/install/pybind11/share/cmake/pybind11)
find_package(pybind11 REQUIRED)

pybind11_add_module(cmake_example src/main.cpp)

# EXAMPLE_VERSION_INFO is defined by setup.py and passed into the C++ code as a
# define (VERSION_INFO) here.
set(EXAMPLE_VERSION_INFO "0.0.1")
target_compile_definitions(cmake_example
                           PRIVATE VERSION_INFO=${EXAMPLE_VERSION_INFO})

编译生成

python .\setup.py bdist_wheel

安装

编译好之后,会在cmake_example目录下生成build, cmake_example.egg-info, dist三个文件夹,我们要的wheel安装包在dist中

pip install ./dist/cmake_example-0.0.1-cp37-cp37m-win_amd64.whl -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

其中cmake_example-0.0.1-cp37-cp37m-win_amd64.whl根据当前python环境不同而不同,记得检查自己的文件名

测试

官方也提供了测试代码,在./tests/test_basic.py

import cmake_example as m

def test_main():
    assert m.__version__ == "0.0.1"
    assert m.add(1, 2) == 3
    assert m.subtract(1, 2) == -1

测试

扫描二维码关注公众号,回复: 16755211 查看本文章
python ./tests/test_basic.py

如果前面有问题导致安装不成功,会出现import失败
在这里插入图片描述
如果安装成功,则不会打印任何东西

参考

https://github.com/pybind/cmake_example
https://pybind11.readthedocs.io/en/stable/compiling.html
https://blog.csdn.net/weixin_44943389/article/details/131547952
https://blog.csdn.net/u011622208/article/details/111302047

主要做激光/影像三维重建,配准、分割等常用点云算法,技术交流、咨询可私信

猜你喜欢

转载自blog.csdn.net/qq_41102371/article/details/132046046