在Ubuntu系統中,C++和Python可以通過多種方式實現交互。以下是一些常見的方法:
Python提供了一個C API,允許C/C++代碼直接調用Python代碼。
編寫C++代碼:
#include <Python.h>
int 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
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))
ctypes
是Python的一個外部函數庫,可以調用動態鏈接庫中的函數。
編寫C++代碼并編譯成共享庫:
// example.cpp
#include <iostream>
extern "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)
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
):
#include <pybind11/pybind11.h>
int 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可能更適合。