在Ubuntu中集成C++與Python可以通過多種方式實現,以下是一些常見的方法:
Python提供了一個C API,允許你從C或C++代碼中調用Python代碼,反之亦然。
編寫C++代碼: 假設你有一個簡單的C++函數:
// mymodule.cpp
#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++代碼為共享庫:
使用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是一個C++庫,可以方便地將C++代碼暴露給Python。
安裝Boost.Python:
sudo apt-get install libboost-python-dev
編寫C++代碼:
// mymodule.cpp
#include <boost/python.hpp>
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是一個輕量級的頭文件庫,用于將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 <pybind11/pybind11.h>
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是一種編程語言,可以將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
以上方法各有優缺點,選擇哪種方法取決于你的具體需求和偏好。