欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

关于C++调用python的代码示例

时间:2023-04-28

#include #include using namespace std;class Py_Operate{public: PyObject *pModule; PyObject *pDict; PyObject *pFunc; PyObject *pArgs; PyByteArrayObject *pImgArr; public: Py_Operate() : pModule(0), pDict(0), pFunc(0),pImgArr(0) { } ~Py_Operate() { Py_DECREF(pArgs); Py_Finalize(); } int PyInit();};

#include "cpp_python.hpp"int Py_Operate::PyInit(){ Py_Initialize(); if (!Py_IsInitialized()) { cout << "Py init :fail" << endl; return 1; } //导入python数组 // _import_array(); //添加当前路径,直接执行字符串的命令 PyRun_SimpleString("import sys"); int i = PyRun_SimpleString("sys.path.append('./')"); // printf("i=%dn", i); // 载入名为request_image的脚本 pModule = Pyimport_importModule("request_image"); if (!pModule) { cout << "pModule:fail" << endl; return 1; } cout << "pModule: " << pModule << endl; // Python模块对象的__dict__属性,得到模块名称空间下的字典对象 pDict = PyModule_GetDict(pModule); if (!pDict) { cout << "pDict:fail" << endl; return 1; } cout << "pDict: " << pDict << endl; // 或者RequestImage函数指针RequestImage pFunc = PyDict_GetItemString(pDict, "RequestImage"); if (!pFunc) { cout << "pFunc:fail" << endl; return 1; } cout << "pFunc: " << pFunc << endl; pArgs = PyTuple_New(1); if (!pArgs) { cout << "pArgs:fail" << endl; return 1; }}

def RequestImage(): # response = requests.get(url="http://192.168.40.42:8080/snapshot?",params="topic=/cam") response = requests.get(url="http://192.168.40.42:8080/snapshot?", params="topic=/cam&width=640&height=480") img = cv.imdecode(np.fromstring(response.content, np.uint8), cv.COLOR_BGR2GRAY) img = cv.flip(img, 1) code_src = pyzbar.decode(img) try: wifi_data=code_src[0].data.decode('utf-8') return wifi_data except Exception: return ""

m_py_object.PyInit();//带参数// PyTuple_SetItem(m_py_object.pArgs, 0, Py_BuildValue("i", 8));// PyObject *pResult=PyObject_CallObject(m_py_object.pFunc,m_py_object.pArgs);//不带参数调用PyObject *pResult = PyObject_CallObject(m_py_object.pFunc, nullptr);if (pResult != NULL){ PyArg_Parse(pResult, "s", &p_wifi_data);//解析参数}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。