心有所向,日复一日,必有精进。|

榴红八色鸫

园龄:3年8个月粉丝:1关注:12

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 中国大陆许可协议进行许可。

posted @   榴红八色鸫  阅读(149)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起