五.C++代码编写
**************************************************
PythonUseC32.h
#ifndef PYTHONUSEC32_H
#define PYTHONUSEC32_H
#include "PythonUseC32_global.h"
#include <pybind11/pybind11.h>
namespace py = pybind11;
class PythonUseC32
{
public:
PythonUseC32();
void hello();
};
int add(int i, int j);
int sub(int i, int j);
#endif // PYTHONUSEC32_H
*************************************************
PythonUseC32.cpp
#include "PythonUseC32.h"
#include <iostream>
PythonUseC32::PythonUseC32()
{
}
void PythonUseC32::hello()
{
std::cout << "hello 2025" << std::endl;
}
int add(int i, int j)
{
return i + j;
}
int sub(int i, int j)
{
return i *j;
}
// 使用 PYBIND11_MODULE 宏来创建 Python 绑定
PYBIND11_MODULE(PythonUseC32, m) {
m.doc() = "pybind11 example plugin"; // 模块的文档字符串
m.def("add", &add, "A function which adds two numbers");
m.def("sub", &sub, "A function which subtracts two numbers");
py::class_<PythonUseC32>(m, "PythonUseC32")
.def(py::init<>())
.def("hello", &PythonUseC32::hello,"A function say hello");
}