在Ubuntu系统中,C++和Python可以通过多种方式实现交互。以下是一些常见的方法:
1. 使用Python的C API
Python提供了一个C API,允许C/C++代码直接调用Python代码。
步骤:
-
编写C++代码:
#includeint main(int argc, char *argv[]) { Py_Initialize(); PyObject *pName = PyUnicode_FromString("hello"); PyObject *pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { PyObject *pFunc = PyObject_GetAttrString(pModule, "say_hello"); if (pFunc && PyCallable_Check(pFunc)) { PyObject_CallObject(pFunc, NULL); } else { PyErr_Print(); } Py_DECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); } Py_Finalize(); return 0; } -
编写Python代码:
def say_hello(): print("Hello from Python!") -
编译C++代码:
g++ -I/usr/include/python3.8 -lpython3.8 your_code.cpp -o your_program -
运行程序:
./your_program
2. 使用SWIG(Simplified Wrapper and Interface Generator)
SWIG是一个软件开发工具,可以从C/C++代码自动生成Python接口。
步骤:
-
安装SWIG:
sudo apt-get install swig -
编写C++代码(例如
example.h):#ifndef EXAMPLE_H #define EXAMPLE_H int add(int a, int b); #endif -
编写SWIG接口文件(例如
example.i):%module example %{ #include "example.h" %} int add(int a, int b); -
生成包装代码:
swig -python example.i -
编译生成的代码:
g++ -c example_wrap.cxx -I/usr/include/python3.8 g++ -shared example_wrap.o -o _example.so -
在Python中使用:
import example print(example.add(3, 4))
3. 使用ctypes
ctypes是Python的一个外部函数库,可以调用动态链接库中的函数。
步骤:
-
编写C++代码并编译成共享库:
// example.cpp #includeextern "C" { int add(int a, int b) { return a + b; } } g++ -fPIC -c example.cpp -o example.o g++ -shared example.o -o libexample.so -
在Python中使用
ctypes调用:import ctypes lib = ctypes.CDLL('./libexample.so') lib.add.argtypes = (ctypes.c_int, ctypes.c_int) lib.add.restype = ctypes.c_int result = lib.add(3, 4) print(result)
4. 使用PyBind11
PyBind11是一个轻量级的头文件库,用于将C++代码暴露给Python。
步骤:
-
安装PyBind11:
git clone https://github.com/pybind/pybind11.git cd pybind11 mkdir build && cd build cmake .. make -j$(nproc) sudo make install -
编写C++代码(例如
example.cpp):#includeint add(int a, int b) { return a + b; } namespace py = pybind11; PYBIND11_MODULE(example, m) { m.def("add", &add, "A function which adds two numbers"); } -
编译C++代码:
g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) -
在Python中使用:
import example print(example.add(3, 4))
选择哪种方法取决于你的具体需求和项目的复杂性。对于简单的交互,ctypes可能是一个不错的选择;而对于更复杂的场景,SWIG或PyBind11可能更适合。
以上就是关于“Ubuntu中C++与Python如何交互”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm