https://docs.python.org/zh-cn/3/c-api/ (中文)
https://docs.python.org/3/extending/embedding.html
https://docs.python.org/zh-cn/3/extending/
安装必要的库
sudo apt install libpython3.10-dev
示例python脚本:
# hello.py
def hello_world():
print("Hello, World from Python!")
配置CMakeLists
:
cmake_minimum_required(VERSION 3.26)
project(lpyl)
set(CMAKE_CXX_STANDARD 11)
add_executable(lpyl main.cpp)
target_link_libraries(
lpyl
PRIVATE
python3.10
)
编写操作代码:
#include
#include
#include
int main() {
std::cout << "Hello, World!" << std::endl;
std::string pythonPathStr = "PYTHONPATH=" + std::string("..");
putenv(const_cast(pythonPathStr.c_str()));
Py_Initialize();
PyObject *pModule = PyImport_ImportModule("hello");
if (pModule) {
PyObject *pFunction = PyObject_GetAttrString(pModule, "hello_world");
if (pFunction && PyCallable_Check(pFunction)) {
PyObject* pArgs = PyTuple_Pack(0);
PyObject* pValue = PyObject_CallObject(pFunction, pArgs);
if (pValue) {
Py_XDECREF(pValue);
} else {
PyErr_Print();
}
Py_XDECREF(pFunction);
} else {
PyErr_Print();
}
Py_XDECREF(pModule);
} else {
PyErr_Print();
}
Py_Finalize();
return 0;
}
输出:
cmake-build-debug/lpyl
Hello, World!
Hello, World from Python!