当我阅读Open3D和Dlib的源代码时,我使用了一个名为pybind11的好东西制作了一个Python库,因此我尝试了一下。
准备
使用
cmake。 pybind11是一个只有标头的库,可以从github(https://github.com/pybind/pybind11/releases)等下载,并按以下目录布局进行排列。
1 2 3 4 | project top |- CMakeLists.txt |- pybind11/ |- mymodule.cpp |
源代码
在
1 2 3 4 5 6 7 8 9 10 11 12 | #include <pybind11/pybind11.h> int add(int a, int b) { return a + b; } PYBIND11_MODULE(mymodule, m) { m.doc() = "my test module"; m.def("add", &add, "add two numbers"); } |
您可以使用宏
第二个参数
构建此文件时,按如下所示创建
1 2 3 4 5 | cmake_minimum_required(VERSION 3.2) project(pybind_test VERSION 0.1.0) add_subdirectory(pybind11) pybind11_add_module(mymodule mymodule.cpp) |
如果按原样构建,将使用默认的Python。如果要针对使用vritualenv或conda创建的特定版本的Python环境进行构建,请提前激活该环境或指定
1 2 3 | import mymodule mymodule.add(1, 10) >> 11 |
分割源文件
当项目扩展或要使用原始C / C代码时,不能在
1 2 3 4 5 6 | project top |- CMakeLists.txt |- pybind11/ |- mymodule.cpp |- lib.cpp |- lib.hpp |
lib.hpp
1 | int add(int a, int b); |
库文件
1 2 3 4 5 6 | #include "lib.hpp" int add(int a, int b) { return a + b; } |
mymodule.cpp
1 2 3 4 5 6 7 8 | #include <pybind11/pybind11.h> #include "lib.hpp" PYBIND11_MODULE(mymodule, m) { m.doc() = "my test module"; m.def("add", &add, "add two numbers"); } |
CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11 | cmake_minimum_required(VERSION 3.2) project(pybind_test VERSION 0.1.0) set(CMAKE_POSITION_INDEPENDENT_CODE ON) add_subdirectory(pybind11) add_library(test lib.cpp) pybind11_add_module(mymodule mymodule.cpp) target_link_libraries(mymodule PRIVATE test) |
点使用
参考
官方文档:https://pybind11.readthedocs.io/en/stable/index.html