ubuntu

Ubuntu C++与Python如何交互

小樊
50
2025-07-28 11:08:34
栏目: 编程语言

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

1. 使用Python的C API

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

C++调用Python

#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, "world"); // 获取函数
        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;
}

在Python中创建一个名为hello.py的文件:

def world():
    print("Hello from Python!")

编译C++代码时需要链接Python库:

g++ -o myapp myapp.cpp $(python3-config --includes --ldflags)

Python调用C++

首先,你需要编写C++代码并封装成Python可调用的模块。

#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);
}

编译C++代码为Python模块:

g++ -fPIC -I/usr/include/python3.8 -o mymodule.so -shared mymodule.cpp $(python3-config --ldflags)

然后在Python中使用这个模块:

import mymodule

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

2. 使用Cython

Cython是一种编程语言,它使得Python代码可以直接转换为C代码,从而可以与C++代码交互。

首先,安装Cython:

pip install cython

然后,创建一个.pyx文件,例如example.pyx

cdef int add(int a, int b):
    return a + b

接下来,创建一个setup.py文件来编译Cython代码:

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("example.pyx")
)

编译Cython代码:

python setup.py build_ext --inplace

现在,你可以在Python中导入并使用这个模块:

import example

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

3. 使用PyBind11

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

首先,安装PyBind11:

pip install pybind11

然后,创建一个C++文件,例如example.cpp

#include <pybind11/pybind11.h>

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");
}

编译C++代码为Python模块:

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

现在,你可以在Python中导入并使用这个模块:

import example

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

这些方法各有优缺点,你可以根据项目需求和个人喜好选择合适的方法。

0
看了该问题的人还看了