安装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)
add_subdirectory(extern/pybind11)
pybind11_add_module(cdemo 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}") message(STATUS "Binary directory: ${CMAKE_BINARY_DIR}")
|
在接下来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))
|
写一个demo.py,如上试试,python demo.py得到结果