本文主要是介绍mingw(Qt) 利用pybind11生成python库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.anaconda 安装创建环境
conda create --name test_pybind
conda activate test_pybind11
conda install pybind11
2.Qt CMake工程
CMakeLists.txt
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
#ifndef MYCLASS_H
#define MYCLASS_Hclass MyClass {
public:MyClass() : value(0) {}void setValue(int val) { value = val; }int getValue() { return value; }int value;
};#endif // MYCLASS_H
MyClass.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
这一步非常重要,否则报错
ImportError: dynamic module does not define module export function
4.python调用
import testpybind11my_obj = testpybind11.MyClass()
my_obj.setValue(10)
print(my_obj.getValue())
这篇关于mingw(Qt) 利用pybind11生成python库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!