美文网首页
利用pybind11给Python写C/C++扩展

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

作者: 小杰杰杰 | 来源:发表于2019-05-07 16:53 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:利用pybind11给Python写C/C++扩展

          本文链接:https://www.haomeiwen.com/subject/uwkyoqtx.html