利用pybind11給Python寫C/C++擴(kuò)展

1.首先準(zhǔn)備工作 安裝pybind11conan

$ 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})
...

接下來開始編譯

$ 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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容