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())
相关推荐
BadBadBad__AK11 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
Warson_L16 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅16 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅16 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L16 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅17 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L17 小时前
python的类&继承
python
Warson_L17 小时前
类型标注/type annotation
python
ThreeS19 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵21 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏