ubuntu

Ubuntu中C++与Python如何交互

小樊
91
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
看了该问题的人还看了