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

posted @ 2022-11-16 14:30  榴红八色鸫  阅读(155)  评论(0)    收藏  举报