python 调用 c++
时间: 2025-07-12 16:03:15 浏览: 16
在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 是一个自动包装器生成工具,支持多种语言,包括 Python 和 C++。适用于已有大型 C++ 项目希望快速暴露接口给 Python 的场景。
假设有一个 `example.i` 接口定义文件:
```swig
%module example
%{
#include "example.h"
%}
int add(int a, int b);
```
对应的 `example.h` 和 `example.cpp` 实现了 `add` 函数。使用 SWIG 生成绑定代码后,再编译为 Python 模块即可调用。
---
##
阅读全文
相关推荐



















