example.cpp和CMakeLists.txt放在test文件夹下面,然后在test文件夹里新建一个build文件夹,运行cmake ..
和 make
,随后会生成一个example.cpython-37m-x86_64-linux-gnu.so
文件,随后将a.py放在build路径下,运行python3 a.py
example.cpp
#include <iostream>
#include <pybind11/pybind11.h>
namespace py = pybind11;
using namespace std;
int add(int a, int b){
return a + b;
}
PYBIND11_MODULE(example, m){
m.doc() = "pybind11 example plugin";
m.def("add", &add, "A function which adds two numbers");
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(test)
set(pybind11_DIR /home/exinova/anaconda3/lib/python3.7/site-packages/pybind11/share/cmake/pybind11)
find_package(pybind11 REQUIRED)
if(${pybind11_FOUND})
message("pybind11 FOUND")
endif()
include_directories(${pybind11_INCLUDE_DIR})
pybind11_add_module(example example.cpp)
target_compile_definitions(example
PRIVATE VERSION_INFO=${EXAMPLE_VERSION_INFO})
a.py
import example
c = example.add(1, 2)
print(c)