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())