1.首先準(zhǔn)備工作 安裝pybind11
和conan
$ pip install pybind11
$ pip install conan
2.下載示例項(xiàng)目
$ git clone https://github.com/memsharded/pybind11-example.git
$ cd pybind11-example
3.在文件conanfile.txt
里你能看到如下內(nèi)容
[requires]
pybind11/1.4@memsharded/stable
[generators]
cmake
這里的 pybind11/1.4@memsharded/stable
并不能夠使用 參考https://github.com/conan-io/conan/issues/2087
檢查你的遠(yuǎn)程倉(cāng)庫(kù):
$ conan --version
$ conan remote list
搜索 pybind11
$ conan search pybind11* -r=conan-center
結(jié)果:
Existing package recipes:
pybind11/2.2.2@conan/stable
pybind11/2.2.3@conan/stable
pybind11/2.2.4@conan/stable
$ conan search pybind11* -r=conan-transit
使用pybind11/2.2.2@conan/stable
替換pybind11/1.4@memsharded/stable
Hello world Python/C++ App
example.cpp:
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
namespace py = pybind11;
PYBIND11_PLUGIN(example) {
py::module m("example", "pybind11 example plugin");
m.def("add", &add, "A function which adds two numbers");
return m.ptr();
}
CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
project(example)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
include_directories(SYSTEM ${CONAN_INCLUDE_DIRS})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
...
接下來(lái)開(kāi)始編譯
$ mkdir build && cd build
#安裝 pybind 包
$ conan install ..
# Cmake編譯
$ cmake .. -DCMAKE_BUILD_TYPE=Release
$ cmake --build .
在Python內(nèi)調(diào)用:
$ python
>>> import example
>>> example.add(2, 3)
5