溫馨提示×

Ubuntu中C++與Python如何交互

小樊
45
2025-05-28 18:13:59
欄目: 編程語言

在Ubuntu系統中,C++和Python可以通過多種方式實現交互。以下是一些常見的方法:

1. 使用Python的C API

Python提供了一個C API,允許C/C++代碼直接調用Python代碼。

步驟:

  1. 編寫C++代碼

    #include <Python.h>
    
    int main(int argc, char *argv[]) {
        Py_Initialize();
    
        PyObject *pName = PyUnicode_FromString("hello");
        PyObject *pModule = PyImport_Import(pName);
        Py_DECREF(pName);
    
        if (pModule != NULL) {
            PyObject *pFunc = PyObject_GetAttrString(pModule, "say_hello");
            if (pFunc && PyCallable_Check(pFunc)) {
                PyObject_CallObject(pFunc, NULL);
            } else {
                PyErr_Print();
            }
            Py_DECREF(pFunc);
            Py_DECREF(pModule);
        } else {
            PyErr_Print();
        }
    
        Py_Finalize();
        return 0;
    }
    
  2. 編寫Python代碼

    def say_hello():
        print("Hello from Python!")
    
  3. 編譯C++代碼

    g++ -I/usr/include/python3.8 -lpython3.8 your_code.cpp -o your_program
    
  4. 運行程序

    ./your_program
    

2. 使用SWIG(Simplified Wrapper and Interface Generator)

SWIG是一個軟件開發工具,可以從C/C++代碼自動生成Python接口。

步驟:

  1. 安裝SWIG

    sudo apt-get install swig
    
  2. 編寫C++代碼(例如example.h):

    #ifndef EXAMPLE_H
    #define EXAMPLE_H
    
    int add(int a, int b);
    
    #endif
    
  3. 編寫SWIG接口文件(例如example.i):

    %module example
    %{
    #include "example.h"
    %}
    
    int add(int a, int b);
    
  4. 生成包裝代碼

    swig -python example.i
    
  5. 編譯生成的代碼

    g++ -c example_wrap.cxx -I/usr/include/python3.8
    g++ -shared example_wrap.o -o _example.so
    
  6. 在Python中使用

    import example
    print(example.add(3, 4))
    

3. 使用ctypes

ctypes是Python的一個外部函數庫,可以調用動態鏈接庫中的函數。

步驟:

  1. 編寫C++代碼并編譯成共享庫

    // example.cpp
    #include <iostream>
    
    extern "C" {
        int add(int a, int b) {
            return a + b;
        }
    }
    
    g++ -fPIC -c example.cpp -o example.o
    g++ -shared example.o -o libexample.so
    
  2. 在Python中使用ctypes調用

    import ctypes
    
    lib = ctypes.CDLL('./libexample.so')
    lib.add.argtypes = (ctypes.c_int, ctypes.c_int)
    lib.add.restype = ctypes.c_int
    
    result = lib.add(3, 4)
    print(result)
    

4. 使用PyBind11

PyBind11是一個輕量級的頭文件庫,用于將C++代碼暴露給Python。

步驟:

  1. 安裝PyBind11

    git clone https://github.com/pybind/pybind11.git
    cd pybind11
    mkdir build && cd build
    cmake ..
    make -j$(nproc)
    sudo make install
    
  2. 編寫C++代碼(例如example.cpp):

    #include <pybind11/pybind11.h>
    
    int add(int a, int b) {
        return a + b;
    }
    
    namespace py = pybind11;
    
    PYBIND11_MODULE(example, m) {
        m.def("add", &add, "A function which adds two numbers");
    }
    
  3. 編譯C++代碼

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

    import example
    print(example.add(3, 4))
    

選擇哪種方法取決于你的具體需求和項目的復雜性。對于簡單的交互,ctypes可能是一個不錯的選擇;而對于更復雜的場景,SWIG或PyBind11可能更適合。

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