欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在 Windows 中使用 pybind11 的教程(python 调用 C++ 代码)

最编程 2024-07-15 09:00:39
...

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

在这里插入图片描述

推荐阅读