溫馨提示×

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

小樊
37
2025-03-29 08:24:11
欄目: 編程語言

在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
    

以上方法各有優缺點,選擇哪種方法取決于你的具體需求和偏好。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女