C++调用python3.7

52 篇文章 2 订阅
29 篇文章 3 订阅

环境:

Ubuntu18.04 + Clion + python3.7 + C++

1. C++主函数tmp.cpp

#include <Python.h>
#include <iostream>
int main(int argc, char *argv[]) {
    Py_SetPythonHome(L"/home/zxq/anaconda3/envs/onnx");
    Py_Initialize();

    //判断初始化是否成功
    if(!Py_IsInitialized())
    {
        printf("Python init failed!\n");
        return -1;
    }

    PyRun_SimpleString("print('Hello world');");
    Py_Finalize();
    return 0;
}

2. CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(test_my_inference_onnx)

set(CMAKE_CXX_STANDARD 14)


include_directories(
        /home/zxq/anaconda3/envs/onnx/include/python3.7m
)
add_executable(test_my_inference_onnx
        tmp.cpp)
target_link_libraries(test_my_inference_onnx
        /home/zxq/anaconda3/envs/onnx/lib/libpython3.7m.so
        )

3. 升级版(调用python接口)

C++主函数:

#include <Python.h>
#include <iostream>

using namespace std;


size_t detector(size_t input_flag){
    Py_SetPythonHome(L"/home/zxq/anaconda3/envs/onnx");
    Py_Initialize();
    //判断初始化是否成功
    size_t CResult;
    if(!Py_IsInitialized())
    {
        printf("Python init failed!\n");
        return -1;
    }
    PyRun_SimpleString("import os, sys");

    PyObject * pModule;
    PyObject * pGetInformationFunc;
    PyRun_SimpleString("sys.path.append('/home/zxq/CLionProjects/test_my_inference_onnx')");
    pModule = PyImport_ImportModule("my_add");
    if (!pModule) {
        throw "The python script cannot be opened.";
    }
    pGetInformationFunc = PyObject_GetAttrString(pModule, "getInformation"); //python function name
    if (NULL == pGetInformationFunc || !PyCallable_Check(pGetInformationFunc))
    {
        throw "The python f cannot be opened.";
    }

    PyObject *pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, PyLong_FromSize_t(input_flag));
    PyObject *PyResult = PyObject_CallObject(pGetInformationFunc, pArgs);
    if (NULL != PyResult){
        CResult = PyLong_AsSize_t(PyResult);
    }

    Py_Finalize();

    return CResult;
}

int main(int argc, char *argv[]) {
    size_t CResult = detector(3);
    printf("%d", CResult);
    return 0;
}

python代码,my_add.py:

def getInformation(a):
    print("+++++++++++++call py success++++++++++++")
    return a+1

4.升级版plus(部署版)

CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(test_my_inference_onnx)

set(CMAKE_CXX_STANDARD 14)

# 包含detect.h路径
SET(INC_DIR  include)
include_directories(${INC_DIR})

include_directories(
        /home/zxq/anaconda3/envs/onnx/include/python3.7m
)
add_executable(test_my_inference_onnx
        tmp.cpp include/detector.cpp include/detector.h)
target_link_libraries(test_my_inference_onnx
        /home/zxq/anaconda3/envs/onnx/lib/libpython3.7m.so
        )

my_add.py 

def getInformation(a):
    print("+++++++++++++call py success++++++++++++")
    return a+1

detector.h头文件



#ifndef TEST_MY_INFERENCE_ONNX_DETECTOR_H
#define TEST_MY_INFERENCE_ONNX_DETECTOR_H

#include <iostream>
#include <string>

using namespace std;
class Detector {
public:
    Detector(const wchar_t *envs_path);
    ~Detector();
    size_t run(size_t flag);

private:
    const wchar_t *envs_path;
public:
    size_t flag;
    size_t c_result;
};

#endif //TEST_MY_INFERENCE_ONNX_DETECTOR_H


detector.cpp



#include "detector.h"
#include <Python.h>
#include <iostream>
//#include <string>


using namespace std;

Detector::Detector(const wchar_t * envs_path_) {
    envs_path = envs_path_;
    Py_SetPythonHome(envs_path);
    Py_Initialize();
}

Detector::~Detector() {
    Py_Finalize();
}

size_t Detector::run(size_t input_flag){
    flag = input_flag;
//    Py_SetPythonHome(envs_path);
    //判断初始化是否成功
    size_t CResult;
    if(!Py_IsInitialized())
    {
        printf("Python init failed!\n");
        return -1;
    }
    PyRun_SimpleString("import os, sys");

    PyObject * pModule;
    PyObject * pGetInformationFunc;
    PyRun_SimpleString("sys.path.append('../')");
//    PyRun_SimpleString("sys.path.append('/home/zxq/CLionProjects/test_my_inference_onnx')");
    pModule = PyImport_ImportModule("my_add");
    if (!pModule) {
        throw "The python script cannot be opened.";
    }
    pGetInformationFunc = PyObject_GetAttrString(pModule, "getInformation"); //python function name
    if (NULL == pGetInformationFunc || !PyCallable_Check(pGetInformationFunc))
    {
        throw "The python f cannot be opened.";
    }

    PyObject *pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, PyLong_FromSize_t(input_flag));
    PyObject *PyResult = PyObject_CallObject(pGetInformationFunc, pArgs);
    if (NULL != PyResult){
        CResult = PyLong_AsSize_t(PyResult);
    }

    return CResult;
}

main.cpp


#include <string>
#include "detector.h"

using namespace std;


int main(int argc, char *argv[]) {
    const wchar_t * envs_path = L"/home/zxq/anaconda3/envs/onnx";
    Detector det(envs_path);
    size_t c_result = det.run(3);

    printf("%d", c_result);
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值