安装pybind11

在当前项目目录下

1
git submodule add -b stable https://github.com/pybind/pybind11.git extern/pybind11

创建demo.cpp

1
2
3
4
5
6
7
8
9
10
11
#include <pybind11/pybind11.h>

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

PYBIND11_MODULE(cdemo, m) {
m.doc() = "pybind11 example plugin"; // 可选的模块文档字符串

m.def("add", &add, "A function which adds two numbers");
}

创建CMakeLists.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
cmake_minimum_required(VERSION 3.10)
project(pybind_example)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON) #强制要求使用指定的 C++ 标准。

# find_package(pybind11 REQUIRED) #这种方式是到系统路径下查找pybind11库,如果找不到,就会报错。
add_subdirectory(extern/pybind11) #而这种方式,是将pybind11库作为一个子目录添加到构建系统中。

pybind11_add_module(cdemo test.cpp) #这里的cdemo是生成的.so文件的名字,test.cpp是要编译的源文件。


install(TARGETS cdemo
LIBRARY DESTINATION ${CMAKE_SOURCE_DIR}
RUNTIME DESTINATION ${CMAKE_SOURCE_DIR}
)

message(STATUS "Project name: ${PROJECT_NAME}")
message(STATUS "Source directory: ${CMAKE_SOURCE_DIR}") #CMakeLists.txt所在的目录
message(STATUS "Binary directory: ${CMAKE_BINARY_DIR}") #cmake编译的目录,build目录

在接下来cmake ..时会看到

— Source directory: /root/codes/deepsketch2
— Binary directory: /root/codes/deepsketch2/build

运行编译

1
2
3
4
5
cd build/
cmake ..
make install
make
make install

此时,会生成诸如 “cdemo.cpython-38-x86_64-linux-gnu.so“这样的文件

python调用

1
2
import cdemo
print(cdemo.add(3, 4)) # Should print 7

写一个demo.py,如上试试,python demo.py得到结果