温馨提示×

Ubuntu下C++与Python如何交互

小樊
40
2025-11-23 12:08:02
栏目: 编程语言

在Ubuntu下,C++和Python可以通过多种方式实现交互。以下是一些常见的方法:

1. 使用Python的C API

Python提供了一个C API,允许C/C++代码直接调用Python代码。

步骤:

  1. 编写C++代码

    // example.cpp
    #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代码

    # hello.py
    def say_hello():
        print("Hello from Python!")
    
  3. 编译C++代码

    g++ -I/usr/include/python3.8 -lpython3.8 example.cpp -o example
    
  4. 运行C++程序

    ./example
    

2. 使用Boost.Python

Boost.Python是一个C++库,允许C++代码与Python代码无缝交互。

步骤:

  1. 安装Boost.Python

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

    // example.cpp
    #include <boost/python.hpp>
    
    char const* greet() {
        return "Hello from C++!";
    }
    
    BOOST_PYTHON_MODULE(hello) {
        using namespace boost::python;
        def("greet", greet);
    }
    
  3. 编译C++代码

    g++ -I/usr/include/python3.8 -lboost_python38 -fPIC example.cpp -o example.so
    
  4. 在Python中使用

    import hello
    print(hello.greet())
    

3. 使用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>
    
    namespace py = pybind11;
    
    int add(int i, int j) {
        return i + j;
    }
    
    PYBIND11_MODULE(example, 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) example.cpp -o example$(python3-config --extension-suffix)
    
  4. 在Python中使用

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

4. 使用SWIG

SWIG(Simplified Wrapper and Interface Generator)是一个软件开发工具,可以从C/C++代码自动生成Python接口。

步骤:

  1. 安装SWIG

    sudo apt-get install swig
    
  2. 编写C++代码

    // example.h
    int add(int i, int j);
    
    // example.cpp
    #include "example.h"
    
    int add(int i, int j) {
        return i + j;
    }
    
  3. 编写SWIG接口文件

    // example.i
    %module example
    %{
    #include "example.h"
    %}
    
    int add(int i, int j);
    
  4. 生成包装代码

    swig -python -py3 example.i
    
  5. 编译C++代码

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

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

选择哪种方法取决于你的具体需求和偏好。Boost.Python和pybind11通常更现代和易用,而Python的C API则更为底层和灵活。

0