环境
C++ 14,Python 3.1 ,使用CMake构建
CMakeLists.txt:
cmake_minimum_required(VERSION 3.22)
project(pythonTest)
# Python环境配置
find_package(Python3 COMPONENTS Interpreter Development REQUIRED)
include_directories(${PYTHON_INCLUDE_DIR})
set(CMAKE_CXX_STANDARD 14)
add_executable(pythonTest main.cpp)
# 不加会导致运行时找不到定义
target_include_directories(${PROJECT_NAME} PRIVATE ${Python3_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} ${Python3_LIBRARIES})
调用
main.cpp
#include <iostream>
#include <Python.h>
int main() {
//初始化Python环境
Py_Initialize();
std::string result;
//追加python文件路径至Python环境
PyObject *sysPath = PySys_GetObject("path");
PyList_Append(sysPath, PyUnicode_FromString("D:/"));
//导入Python文件
PyObject *pModule = PyImport_ImportModule("c_plus_test");
if (pModule != NULL) {
//获取函数
PyObject *pFunc = PyObject_GetAttrString(pModule, "call_python");
if (pFunc != NULL) {
PyObject *myResult = PyObject_CallObject(pFunc, NULL);
//转换结果至c++字符串
result = PyUnicode_AsUTF8(myResult);
Py_DECREF(myResult);
} else {
std::cout << "call python function fail!!!!" << std::endl;
}
Py_DECREF(pFunc);
} else {
std::cout << "import module fail!!!!" << std::endl;
}
std::cout << "get python reault:" << result << std::endl;
//释放资源
Py_DECREF(sysPath);
Py_DECREF(pModule);
Py_Finalize();
return 0;
}
Python3中去掉了PyString_AsString使用PyUnicode_AsUTF8转换字符串
c_plus_test.py
import os
def call_python():
helloStr = "Hello in Python";
print('Hello in Python');
return helloStr;
参考资料
https://zhuanlan.zhihu.com/p/149887203
https://blog.csdn.net/iamqianrenzhan/article/details/86516440