1. 下载pybind11
gittub中下载,pybind下载后解压
2. C++生成库文件
- 2.1.VS新建空白工程,工程名随意起
- 2.2更改目标文件名和配置类型
- 2.3更改目标文件拓展名
- 2.4添加include路径和库路径
包含目录中添加刚刚下载好的pybind的include路径以及pyhon的include文件,这里我使用的时Anaconda的下python的include:
E:\Software\pybind11-master\include
E:\ProgramData\Anaconda3\include
库目录为:
E:\ProgramData\Anaconda3\libs
- 2.5添加依赖项
链接器中输入E:\ProgramData\Anaconda3\libs
下的lib名
- 2.6添加main.cpp文件
#include "pybind11/pybind11.h"
#include "pybind11/stl.h" // 用于处理STL容器
#include "pybind11/operators.h" // 用于支持自定义结构体的操作
struct MyStruct {
int x;
int y;
};
int add(const MyStruct& s) {
return s.x + s.y;
}
namespace py = pybind11;
PYBIND11_MODULE(example, m) {
m.doc() = "add plugin";
py::class_<MyStruct>(m, "MyStruct")
.def(py::init<int, int>()) // 构造函数
.def_readwrite("x", &MyStruct::x) // x 成员变量
.def_readwrite("y", &MyStruct::y); // y 成员变量
m.def("add", &add, "add function (s: MyStruct)"); // 修改函数签名,接受 MyStruct 作为参数
}
注意main.cpp文件中PYBIND11_MODULE(example, m)
的example要与目标文件名一致
- 2.7编译
无法启动是正常的,工程目录下的release路径找到example.pyd
3.Python调用
- 3.1python中安装pybind11
pip install pybind11 -i https://pypi.tuna.tsinghua.edu.cn/simple
将example.pyd放到与test.py同目录下
- 3.2运行test.py
import example
s = example.MyStruct(10, 20)
result = example.add(s)
print(result) # 输出 30