不同版本python 调用 C++ 接口

这篇博客记录了在Ubuntu操作系统中,如何使用Python2.x和Python3.x调用C++编写的动态库。详细介绍了C++代码编译为动态库的步骤以及在Python中导入并使用这些库的方法。

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

最近ubantu上做python项目用到了C++接口,觉着有点意思,特记录一下。

这里将会介绍python2.x 和 python 3.x 调用C++接口的方法:

话不多说,

1、python2.x

 C++ 文件名 test.cpp

#include <Python.h>

static PyObject * Add(PyObject * self, PyObject * args)
{
    int x, y;
    if(!PyArg_ParseTuple(args, "ii", &x, &y)) return NULL;
    int out = x + y;
    return Py_BuildValue("i", out);
}

static PyMethodDef testMethods[] = {
    {"Add", Add, METH_VARARGS, "add function"}
    {NULL, NULL, 0, NULL}   /* Sentinel */
}

extern "C"
void inittest(){
    Py_InitModule("test", testMethods);
}

ubantu编译成动态库命令

g++ test.cpp -fPIC -shared -o test.so -I/usr/include/python2.7 -lboost_python

python调用

  直接进入 test.so所在目录,在python文件中使用import test即可像普通module一般调用。

2、python3.x

#include <Python.h>

static PyObje
### Python 调用 C++ API 的方法 #### 使用 `pybind11` 实现 Python 调用 C++ 以下是基于 `pybind11` 的实现方式: 首先,确保安装了必要的工具链并编译生成共享库。命令如下所示[^1]: ```bash g++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` your.cpp -o py2cpp`python3-config --extension-suffix` -I /usr/include/python3.6m ``` 假设有一个简单的 C++ 函数定义为: ```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_MODULE` 是用于绑定模块的关键宏。在 Python 中可以通过以下方式进行调用: ```python import example result = example.add(1, 2) print(result) # 输出:3 ``` --- #### 使用 `ctypes` 实现 Python 调用 C++ 对于 `ctypes` 方法,需注意其仅支持调用具有 C 风格接口的函数。因此,在 C++ 文件中需要使用 `extern "C"` 关键字来防止名称修饰。 以下是一个完整的例子][^[^23]: ##### 编写 C++ 文件 (myCtype.cpp) ```cpp extern "C" int Add(int a, int b) { return a + b; } ``` ##### 编译成共享库 在 Linux 下执行以下命令将其编译为共享库: ```bash g++ -shared -fPIC myCtype.cpp -o libmyctype.so ``` ##### 在 Python 中加载共享库并调用 ```python import ctypes # 加载共享库 lib = ctypes.CDLL('./libmyctype.so') # 设置返回值类型 lib.Add.restype = ctypes.c_int # 设置参数类型 lib.Add.argtypes = [ctypes.c_int, ctypes.c_int] # 调用函数 result = lib.Add(1, 2) print(result) # 输出:3 ``` 如果涉及字符串传递,则可以参考以下示例[^4]: ```python lib.greet.restype = ctypes.c_char_p lib.greet.argtypes = [ctypes.c_char_p] result = lib.greet(b"Python") print(result.decode()) ``` --- ### 总结 两种方法各有优劣: - **PyBind11**: 更加灵活,可以直接暴露复杂的 C++ 类型给 Python。 - **CTypes**: 较简单,适合只调用基本功能的情况,但不支持复杂数据结构。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值