Skip to content

Instantly share code, notes, and snippets.

@nanmi
Last active June 15, 2021 04:51
Show Gist options
  • Save nanmi/3e63cd1a1d27ab5769ea37330c28b0f3 to your computer and use it in GitHub Desktop.
Save nanmi/3e63cd1a1d27ab5769ea37330c28b0f3 to your computer and use it in GitHub Desktop.
pybind11编译和使用

pybind11编译和使用

download pybind11 project

$ git clone https://github.com/pybind/pybind11.git

install pytest

$ pip install pytest

build

$ cd pybind11
$ mkdir build;cd build;cmake ..
$ cmake --build . --config Release --target check

新建一个pybind11,把mock_install/include/pybind11所有内容copy到新建的pybind11,把mock_install/share/cmake文件加copy到新建的pybind11

新建add.cpp

#include "pybind11/pybind11.h"
namespace py = pybind11;
 
int add(int i, int j)
{
    return i + j;
}
 
PYBIND11_MODULE(add, m)
{
    // optional module docstring
    m.doc() = "pybind11 example plugin";
    // expose add function, and add keyword arguments and default arguments
    m.def("add", &add, "A function which adds two numbers", py::arg("i")=1, py::arg("j")=2);
 
    // exporting variables
    m.attr("the_answer") = 42;
    py::object world = py::cast("World");
    m.attr("what") = world;
}

新建CMakeLists.txt

cmake_minimum_required(VERSION 3.2.1)
project(example)

include(pybind11/cmake/FindPythonLibsNew.cmake)
include(pybind11/cmake/pybind11Config.cmake)
include(pybind11/cmake/pybind11ConfigVersion.cmake)
include(pybind11/cmake/pybind11Targets.cmake)
include(pybind11/cmake/pybind11Tools.cmake)

#这一句一定要,编译要用release模式,不设的话,默认是debug,速度慢很多 
set(CMAKE_BUILD_TYPE "Release")

pybind11_add_module(add add.cpp)

新建test.py

import add

print(add.add(1, 5))
print(add.the_answer)
print(add.what)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment