pybind使用 | Jason Hao's Blog
0%

pybind使用

Pybind11 主要的思想

image-20210426165542076

Pybind11 环境配置

  1. 下载pybind11 https://github.com/pybind/pybind11 解压到 C:-master,解压后就可以直接使用(head-only)

  2. Windows 软件 Visual Studio 2017 (VS2017), Python3.6

  3. Python中安装:pip install pybind11

  4. VS2017 配置:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    1)设置编译输出类型 
    配置属性--常规--常规--目标文件扩展名:.pyd
    配置属性--常规--项目默认值-配置类型:动态库.dll

    2)添加include包含:
    配置属性--VC++目录--常规--包含目录:
    C:\pybind11-master\include // 这个是pybind的include目录
    C:\ProgramData\Anaconda3\envs\python36\indclude //这个是python环境的include目录,你也可以用anaconda自带的环境

    3) lib 路径:
    配置属性--VC++目录-库目录:
    C:\ProgramData\Anaconda3\envs\python36\libs //这个是python环境的libs目录,你也可以用anaconda自带的环境

    4)链接器配置:
    链接器-输入-附加依赖项:
    python3.lib
    python36.lib
  5. Pycharm 配置:

    1
    2
    1) 注意配置的 Python 解释器的版本 (比如这里是 3.6)
    2) 注意配置的 Python 解释器是否安装了 pybind11

Pybind11 Python 调用 C++

  1. C++ code
1
2
3
4
5
6
7
8
9
10
11
#include <pybind11/pybind11.h>
#include "example1.h"

namespace py = pybind11;

int add(int i, int j) {return i + j;}

PYBIND11_MODULE(example, m) { //"example" is python module name
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers"); // "add" is method name
}
  1. VS2017 compiling...

produced a XXX.pyd file in directory “dir” (XXX is the C++ project name)

change XXX to the module name so that can be used in Python

  1. Python use module provided by C++

3.1 using with sys.path

1
2
3
4
import sys
sys.path.append("dir") # dir includes the XXX.pyd file
import example # defined module name
example.add() # use the method from the module

3.2 use with setuptools

write a setup.py file in the dir of the .cpp file

1
2
3
4
5
6
7
8
9
10
11
from setuptools import setup, Extension

functions_module = Extension(
name ='example',
sources = ['first_pybind.cpp'],
include_dirs = ['F:\\Anaconda\\Anaconda3_201910\\envs\\env_pybind11\\lib\\site-packages\\pybind11\\include',
'F:\\Anaconda\\Anaconda3_201910\\envs\\env_pybind11\\include']
# include_dirs 中的路径 更改为自己虚拟环境下相应 pybind11的路径 和 python的include路径
)

setup(ext_modules = [functions_module])
1
2
cd dir of (.cpp file and setup.py file)
python setup.py build_ext --inplace
1
2
import example
print(example.add(1, 2))
  1. 注意: 在 C++ 中使用的 module name 也就是上面代码中的 example 要和 Python 代码中 import 的 module name 一样,否则会报错 “DLL load failed”

参考 (References)

  1. 使用 pybind11 包装 C++ 类