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())
相关推荐
aini_lovee2 小时前
python在容器内克隆拉取git私有仓库
git·python·elasticsearch
@老蝴2 小时前
C语言 — 通讯录模拟实现
c语言·开发语言·算法
♚卜卦4 小时前
面向对象 设计模式简述(1.创建型模式)
开发语言·设计模式
安全系统学习4 小时前
网络安全之RCE简单分析
开发语言·python·算法·安全·web安全
Swift社区5 小时前
Swift 解法详解:如何在二叉树中寻找最长连续序列
开发语言·ios·swift
yutian06066 小时前
C# 支持 ToolTip 功能的控件,鼠标悬停弹提示框
开发语言·microsoft·c#
蹦蹦跳跳真可爱5896 小时前
Python----神经网络发(神经网络发展历程)
人工智能·python·深度学习·神经网络·计算机视觉
byte轻骑兵6 小时前
【C++特殊工具与技术】优化内存分配(四):定位new表达式、类特定的new、delete表达式
开发语言·c++
chao_7896 小时前
标注工具核心代码解析——class AnnotationVie【canvas.py]
开发语言·python·qt5
YuTaoShao6 小时前
Java八股文——JVM「内存模型篇」
java·开发语言·jvm