mingw(Qt) 利用pybind11生成python库

1.anaconda 安装创建环境

bash 复制代码
conda create --name test_pybind
conda activate test_pybind11
conda install pybind11

2.Qt CMake工程

CMakeLists.txt

bash 复制代码
cmake_minimum_required(VERSION 3.5)

project(testpybind11 LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(PYTHON_EXECUTABLE "C:/Users/93551/.conda/envs/test_pybind11/python.exe")
set(PYTHON_INCLUDE_DIR "C:/Users/93551/.conda/envs/test_pybind11/include")
set(PYTHON_LIBRARY "C:/Users/93551/.conda/envs/test_pybind11/libs")

set(pybind11_DIR "C:/Users/93551/.conda/envs/test_pybind11/Lib/site-packages/pybind11/share/cmake/pybind11")

include_directories(${PYTHON_INCLUDE_DIR})
link_directories(${PYTHON_LIBRARY})


find_package(Python REQUIRED)
find_package(pybind11 REQUIRED)
add_library(testpybind11 SHARED Myclass.cpp)
target_link_libraries(testpybind11  python3.lib python312.lib)

# 后缀名改成pyd能够被python引用
set_target_properties(testpybind11 PROPERTIES SUFFIX ".pyd")

MyClass.h

cpp 复制代码
#ifndef MYCLASS_H
#define MYCLASS_H


class MyClass {
public:
    MyClass() : value(0) {}
    void setValue(int val) { value = val; }
    int getValue() { return value; }
    int value;
};


#endif // MYCLASS_H

MyClass.cpp

cpp 复制代码
#include "MyClass.h"
#include "Python.h"

#include <pybind11-global/pybind11/pybind11.h>
#include <pybind11-global/pybind11/eval.h>
#include <pybind11-global/pybind11/embed.h>
namespace py = pybind11;
using namespace py;

PYBIND11_MODULE(testpybind11, m) {
    py::class_<MyClass>(m, "MyClass")
        .def(py::init<>())
        .def("setValue", &MyClass::setValue)
        .def("getValue", &MyClass::getValue);
}

3.将生成的libtestpybind11.pyd为testpybind11.pyd

这一步非常重要,否则报错

python 复制代码
ImportError: dynamic module does not define module export function

4.python调用

python 复制代码
import testpybind11
 my_obj = testpybind11.MyClass()
my_obj.setValue(10)
print(my_obj.getValue())
相关推荐
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
weilx12345 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫5 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技5 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛5 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
只睡四小时5 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas