利用pybind11给Python写C/C++扩展

1.首先准备工作 安装pybind11conan

$ pip install pybind11
$ pip install conan

2.下载示例项目

$ git clone https://github.com/memsharded/pybind11-example.git
$ cd pybind11-example

3.在文件conanfile.txt里你能看到如下内容

[requires]
pybind11/1.4@memsharded/stable

[generators]
cmake

这里的 pybind11/1.4@memsharded/stable并不能够使用 参考https://github.com/conan-io/conan/issues/2087

检查你的远程仓库:

$ conan --version
$ conan remote list

搜索 pybind11

$ conan search pybind11* -r=conan-center
结果:
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内调用:

$ python
>>> import example
>>> example.add(2, 3)
5
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容