在Ubuntu中集成C++与Python可以通过多种方式实现,以下是一些常见的方法:
方法一:使用Python的C API
Python提供了一个C API,允许你从C或C++代码中调用Python代码,反之亦然。
-
编写C++代码: 假设你有一个简单的C++函数:
// mymodule.cpp #include
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++代码为共享库: 使用
g++
编译C++代码为共享库:g++ -fPIC -I/usr/include/python3.8 -lpython3.8 -o mymodule.so mymodule.cpp
-
在Python中使用C++模块: 在Python中导入并使用编译好的C++模块:
import mymodule result = mymodule.add(3, 4) print(result) # 输出 7
方法二:使用Boost.Python
Boost.Python是一个C++库,可以方便地将C++代码暴露给Python。
-
安装Boost.Python:
sudo apt-get install libboost-python-dev
-
编写C++代码:
// mymodule.cpp #include
char const* greet() { return "hello, world"; } BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } -
编译C++代码为共享库:
g++ -I/usr/include/python3.8 -lboost_python38 -fPIC -o hello_ext.so mymodule.cpp
-
在Python中使用C++模块:
import hello_ext print(hello_ext.greet()) # 输出 hello, world
方法三:使用pybind11
pybind11是一个轻量级的头文件库,用于将C++代码暴露给Python。
-
安装pybind11: 你可以从GitHub克隆pybind11并编译安装:
git clone https://github.com/pybind/pybind11.git cd pybind11 mkdir build && cd build cmake .. make -j$(nproc) sudo make install
-
编写C++代码:
// mymodule.cpp #include
int add(int i, int j) { return i + j; } namespace py = pybind11; PYBIND11_MODULE(mymodule, m) { m.doc() = "pybind11 example plugin"; // Optional module docstring m.def("add", &add, "A function which adds two numbers"); } -
编译C++代码为共享库:
g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) mymodule.cpp -o mymodule$(python3-config --extension-suffix)
-
在Python中使用C++模块:
import mymodule result = mymodule.add(3, 4) print(result) # 输出 7
方法四:使用Cython
Cython是一种编程语言,可以将Python代码转换为C代码,并且可以与C++代码集成。
-
安装Cython:
pip install cython
-
编写C++代码:
// mymodule.cpp extern "C" { int add(int a, int b) { return a + b; } }
-
编写Cython接口文件:
# mymodule.pyx cdef extern from "mymodule.cpp": int add(int a, int b) def py_add(int a, int b): return add(a, b)
-
编写setup.py:
from setuptools import setup from Cython.Build import cythonize setup( ext_modules=cythonize("mymodule.pyx"), include_dirs=[], libraries=["mymodule"], library_dirs=[] )
-
编译Cython代码:
python setup.py build_ext --inplace
-
在Python中使用C++模块:
import mymodule result = mymodule.py_add(3, 4) print(result) # 输出 7
以上方法各有优缺点,选择哪种方法取决于你的具体需求和偏好。