1,介绍
pybind11是一个只有头文件的轻量级库,它向Python暴露了C++的类型同时也向C++暴露了Python类型,pybind11主要用于创建现有C++代码的Python绑定。
1,安装要求
1.1 gcc版本
GCC 4.8或更新版本
sudo apt-get install gcc-4.8 cmake
conda install pytest
1.2 编译pybind11
git clone https://github.com/pybind/pybind11.git
mkdir build
cd build
cmake ..
cmake --build . --config Release --target check
make check -j 4
2,程序
2.1 example.cpp
#include <include/pybind11/pybind11.h>
#include <include/pybind11/stl.h>
#include <vector>
int add(int i, int j)
{
return i+j;
}
// python程序入口
namespace py = pybind11;
PYBIND11_MODULE(example,m)
{
m.doc() = "pybind11 example plugin";
m.def("add", &add, "two integer add");
}
2.2 makefile
CXXFLAGS = -std=gnu++11 -O3 -shared -fPIC
LDFLAGS = $(shell python3-config --cflags --ldflags --libs)
PYBIND11 = path/to/pybind11/include
CXX_SOURCES = example.cpp
LIB_SO = example.so
$(LIB_SO): $(CXX_SOURCES)
@$(CXX) $(CXXFLAGS) -I $(PYBIND11) $(LDFLAGS) -o $@ $(CXX_SOURCES)
clean:
rm -rf $(LIB_SO)
只要pybind11中的include,注意include
2.3 test.py
import example
out = example.add(1,2)
print(out)
3