c++调用python
cmakelists
cmake_minimum_required(VERSION 3.20) project(python_test) #python set(Python3_ROOT_DIR "/home/ubuntu/miniconda3/envs/python38") set(PYTHON_INCLUDE_DIRS "/home/ubuntu/miniconda3/envs/python38/include/python3.8") find_package(Python3 COMPONENTS Interpreter NumPy REQUIRED) INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_DIRS}) link_directories(/home/ubuntu/miniconda3/envs/python38/lib/python3.8/config-3.8-x86_64-linux-gnu) set(PYTHON_LIBRARIES "/home/ubuntu/miniconda3/envs/python38/lib/libpython3.8.so") #opencv set(OpenCV_DIR /usr/lib/x86_64-linux-gnu/cmake/opencv4) find_package(OpenCV REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) add_executable(test testcpp.cpp) target_link_libraries(test ${PYTHON_LIBRARIES} Python3::NumPy ${OpenCV_LIBS})
test2.py (不能用test.py命名)
def testcpp(): import torch print(torch.cuda.is_available())
testcpppy.cpp
#include <Python.h> #include <iostream> int main(){ Py_Initialize(); //初始化 if (!Py_IsInitialized()) { return -1; //init python failed } //相当于在python中的import sys语句。这个函数是宏,相当于直接运行python语句 PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('../')");//是将搜索路径设置为当前目录。 PyObject *pmodule = PyImport_ImportModule("test2"); //导入hello.py if (!pmodule) { printf("cannot find test.py\n"); return -1; } else { printf("PyImport_ImportModule success\n"); } PyObject *pfunc = PyObject_GetAttrString(pmodule, "testcpp"); //导入func1函数 if (!pfunc) { printf("cannot find func\n"); Py_XDECREF(pmodule); return -1; } else { printf("PyObject_GetAttrString success\n"); } //调用python脚本函数 PyObject *pArgs = NULL; PyObject *pResult = PyObject_CallObject(pfunc, pArgs); //释放资源 Py_XDECREF(pmodule); Py_XDECREF(pfunc); Py_XDECREF(pArgs); Py_Finalize(); return 0; }
参考资料
https://blog.csdn.net/weixin_45066336/article/details/124148058
https://blog.csdn.net/kevinshift/article/details/126810726 (有图片的例子)
https://blog.csdn.net/m0_46656879/article/details/124490820
https://blog.csdn.net/king52113141314/article/details/108363939
本文作者:榴红八色鸫
本文链接:https://www.cnblogs.com/hezexian/p/16895812.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步