Python调用c++

本文介绍了如何使用Python调用C++代码,详细讲解了通过SWIG工具对C和C++库进行包装的步骤,包括编写.i文件、使用swig命令生成Python包前身、编译生成Python模块动态库,并提供了直接使用Linux编译器和利用python.distutils两种编译方法。最后展示了在Python环境中成功导入并使用生成的.so模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python与c++通信,作者描述了Python与c++相互通信的方法,依据文章所述,做了相关的实验,在此转述作者文章并记录自己的学习过程。
1. Python调用c++(基础篇)
2. Python调用c++(高级篇,使用swig工具)

Python调用c++

作者:Jerry Jho
链接:https://www.zhihu.com/question/23003213/answer/56121859
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

这种做法称为Python扩展。比如说,我们有一个功能强大的C函数:int great_function(int a) {
return a + 1;
}
期望在Python里这样使用:

from great_module import great_function
great_function(2)
3

考虑最简单的情况。我们把功能强大的函数放入C文件 great_module.c 中。

#include <Python.h>

int great_function(int a) {
    return a + 1;
}

static PyObject * _great_function(PyObject *self, PyObject *args)
{
    int _a;
    int res;

    if (!PyArg_ParseTuple(args, "i", &_a))
        return NULL;
    res = great_function(_a);
    return PyLong_FromLong(res);
}

static PyMethodDef GreateModuleMethods[] = {
    {
        "great_function",
        _great_function,
        METH_VARARGS,
        ""
    },
    {
  
  NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initgreat_module(void) {
    (void) Py_InitModule("great_module", GreateModuleMethods);
}

除了功能强大的函数great_function外,这个文件中还有以下部分:

  • 包裹函数_great_function。它负责将Python的参数转化为C的参数(PyArg_ParseTuple),调用实际的great_function,并处理great_function的返回值,最终返回给Python环境。
  • 第三个参数的含义是参数变长,第四个参数是一个说明性的字符串。导出表总是以{NULL, NULL, 0, NULL}结束。
  • 导出函数initgreat_module。这个的名字不是任取的,是你的module名称添加前缀init。导出函数中将模块名称与导出表进行连接。

从上

Python调用C++代码可以通过多种方法实现,主要包括使用扩展模块、C/C++接口封装以及工具链辅助生成绑定代码等方式。以下是几种常见且实用的方案: ### 1. 使用 `ctypes` 调用 C 风格共享库 虽然 `ctypes` 主要用于调用 C 编写的动态链接库(如 `.so` 或 `.dll`),但可以通过将 C++ 代码编译为具有 `extern "C"` 导出符号的共享库来间接调用 C++ 函数。 ```cpp // hello.cpp #include <iostream> extern "C" { void greet() { std::cout << "Hello from C++!" << std::endl; } } ``` 编译为共享库: ```bash g++ -shared -fPIC -o libhello.so hello.cpp ``` 然后在 Python调用: ```python import ctypes lib = ctypes.CDLL('./libhello.so') lib.greet() ``` ### 2. 使用 `Boost.Python` 创建 Python 扩展 `Boost.Python` 是一个功能强大的库,允许你直接将 C++ 类和函数暴露给 Python。它需要安装 Boost 库并进行适当的配置。 ```cpp // example.cpp #include <boost/python.hpp> char const* greet() { return "Hello from C++ with Boost.Python!"; } BOOST_PYTHON_MODULE(example) { using namespace boost::python; def("greet", greet); } ``` 编译命令示例: ```bash g++ -I/usr/include/python3.8 -I/usr/local/include/boost -fPIC -shared example.cpp -o example.so -lboost_python38 -lpython3.8 ``` 然后在 Python 中导入并使用: ```python import example print(example.greet()) ``` ### 3. 使用 `pybind11` 构建轻量级绑定 `pybind11` 是一个现代、轻量级的头文件库,专为简化 C++Python 的交互而设计,推荐用于新项目。 ```cpp // main.cpp #include <pybind11/pybind11.h> int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m) { m.def("add", &add, "A function that adds two numbers"); } ``` 编译命令(确保已安装 pybind11): ```bash c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) main.cpp -o example$(python3-config --extension-suffix) ``` Python 中使用: ```python import example print(example.add(3, 4)) # 输出 7 ``` ### 4. 使用 SWIG 自动生成绑定代码 SWIG 是一个自动包装器生成工具,支持多种语言,包括 PythonC++。适用于已有大型 C++ 项目希望快速暴露接口给 Python 的场景。 假设有一个 `example.i` 接口定义文件: ```swig %module example %{ #include "example.h" %} int add(int a, int b); ``` 对应的 `example.h` 和 `example.cpp` 实现了 `add` 函数。使用 SWIG 生成绑定代码后,再编译为 Python 模块即可调用。 --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值