python跟c++混合编程

发布于:2025-02-10 ⋅ 阅读:(26) ⋅ 点赞:(0)

Python 有几种方式可以与 C++ 混合编程,我列举主要的方法:

1. Cython (推荐)

Cython 允许你直接在 Python 代码中编写 C/C++ 代码。

# example.pyx
cdef extern from "math.h":
    double sqrt(double x)

# 定义 C++ 函数
cdef double cpp_function(double x) nogil:
    return sqrt(x * x + 1.0)

# Python 可调用的函数
def py_function(x):
    return cpp_function(x)
# setup.py
from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("example.pyx")
)

5. 完整示例:使用 pybind11

// mathlib.cpp
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
#include <string>

namespace py = pybind11;

class Calculator {
public:
    Calculator() {}

    double add(double a, double b) {
        return a + b;
    }

    std::vector<double> multiply_array(const std::vector<double>& arr, double factor) {
        std::vector<double> result;
        for(const auto& val : arr) {
            result.push_back(val * factor);
        }
        return result;
    }

    std::string get_info() {
        return "C++ Calculator";
    }
};

PYBIND11_MODULE(mathlib, m) {
    py::class_<Calculator>(m, "Calculator")
        .def(py::init<>())
        .def("add", &Calculator::add)
        .def("multiply_array", &Calculator::multiply_array)
        .def("get_info", &Calculator::get_info);
}

网站公告

今日签到

点亮在社区的每一天
去签到