如何在Ubuntu中集成C++与Python

1032
2025/3/29 9:31:43
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu中集成C++与Python可以通过多种方式实现,以下是一些常见的方法:

方法一:使用Python的C API

Python提供了一个C API,允许你从C或C++代码中调用Python代码,反之亦然。

  1. 编写C++代码: 假设你有一个简单的C++函数:

    // mymodule.cpp
    #include <Python.h>
    
    static PyObject* add(PyObject* self, PyObject* args) {
        int a, b;
        if (!PyArg_ParseTuple(args, "ii", &a, &b)) {
            return NULL;
        }
        return Py_BuildValue("i", a + b);
    }
    
    static PyMethodDef MyMethods[] = {
        {"add", add, METH_VARARGS, "Add two numbers"},
        {NULL, NULL, 0, NULL}
    };
    
    static struct PyModuleDef mymodule = {
        PyModuleDef_HEAD_INIT,
        "mymodule",
        NULL,
        -1,
        MyMethods
    };
    
    PyMODINIT_FUNC PyInit_mymodule(void) {
        return PyModule_Create(&mymodule);
    }
    
  2. 编译C++代码为共享库: 使用g++编译C++代码为共享库:

    g++ -fPIC -I/usr/include/python3.8 -lpython3.8 -o mymodule.so mymodule.cpp
    
  3. 在Python中使用C++模块: 在Python中导入并使用编译好的C++模块:

    import mymodule
    
    result = mymodule.add(3, 4)
    print(result)  # 输出 7
    

方法二:使用Boost.Python

Boost.Python是一个C++库,可以方便地将C++代码暴露给Python。

  1. 安装Boost.Python

    sudo apt-get install libboost-python-dev
    
  2. 编写C++代码

    // mymodule.cpp
    #include <boost/python.hpp>
    
    char const* greet() {
        return "hello, world";
    }
    
    BOOST_PYTHON_MODULE(hello_ext) {
        using namespace boost::python;
        def("greet", greet);
    }
    
  3. 编译C++代码为共享库

    g++ -I/usr/include/python3.8 -lboost_python38 -fPIC -o hello_ext.so mymodule.cpp
    
  4. 在Python中使用C++模块

    import hello_ext
    
    print(hello_ext.greet())  # 输出 hello, world
    

方法三:使用pybind11

pybind11是一个轻量级的头文件库,用于将C++代码暴露给Python。

  1. 安装pybind11: 你可以从GitHub克隆pybind11并编译安装:

    git clone https://github.com/pybind/pybind11.git
    cd pybind11
    mkdir build && cd build
    cmake ..
    make -j$(nproc)
    sudo make install
    
  2. 编写C++代码

    // mymodule.cpp
    #include <pybind11/pybind11.h>
    
    int add(int i, int j) {
        return i + j;
    }
    
    namespace py = pybind11;
    
    PYBIND11_MODULE(mymodule, m) {
        m.doc() = "pybind11 example plugin"; // Optional module docstring
        m.def("add", &add, "A function which adds two numbers");
    }
    
  3. 编译C++代码为共享库

    g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) mymodule.cpp -o mymodule$(python3-config --extension-suffix)
    
  4. 在Python中使用C++模块

    import mymodule
    
    result = mymodule.add(3, 4)
    print(result)  # 输出 7
    

方法四:使用Cython

Cython是一种编程语言,可以将Python代码转换为C代码,并且可以与C++代码集成。

  1. 安装Cython

    pip install cython
    
  2. 编写C++代码

    // mymodule.cpp
    extern "C" {
        int add(int a, int b) {
            return a + b;
        }
    }
    
  3. 编写Cython接口文件

    # mymodule.pyx
    cdef extern from "mymodule.cpp":
        int add(int a, int b)
    
    def py_add(int a, int b):
        return add(a, b)
    
  4. 编写setup.py

    from setuptools import setup
    from Cython.Build import cythonize
    
    setup(
        ext_modules=cythonize("mymodule.pyx"),
        include_dirs=[],
        libraries=["mymodule"],
        library_dirs=[]
    )
    
  5. 编译Cython代码

    python setup.py build_ext --inplace
    
  6. 在Python中使用C++模块

    import mymodule
    
    result = mymodule.py_add(3, 4)
    print(result)  # 输出 7
    

以上方法各有优缺点,选择哪种方法取决于你的具体需求和偏好。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Ubuntu dhclient命令行使用技巧